How to pass parameters to PHP template rendered with 'include'?

前端 未结 3 1609
醉话见心
醉话见心 2021-02-01 07:32

need your help with PHP templating. I\'m new to PHP (I\'m coming from Perl+Embperl). Anyway, my problem is simple:

  • I have a small template to render some item, let
相关标签:
3条回答
  • 2021-02-01 07:48

    I use the following helper functions when I work on simple websites:

    function function_get_output($fn)
    {
      $args = func_get_args();unset($args[0]);
      ob_start();
      call_user_func_array($fn, $args);
      $output = ob_get_contents();
      ob_end_clean();
      return $output;
    }
    
    function display($template, $params = array())
    {
      extract($params);
      include $template;
    }
    
    function render($template, $params = array())
    {
      return function_get_output('display', $template, $params);
    }
    

    display will output the template to the screen directly. render will return it as a string. It makes use of ob_get_contents to return the printed output of a function.

    0 讨论(0)
  • 2021-02-01 08:06

    $param should be already available inside the template. When you include() a file it should have the same scope as where it was included.

    from http://php.net/manual/en/function.include.php

    When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward. However, all functions and classes defined in the included file have the global scope.

    You could also do something like:

    print render("/templates/blog_entry.php", array('row'=>$row));
    
    function render($template, $param){
       ob_start();
       //extract everything in param into the current scope
       extract($param, EXTR_SKIP);
       include($template);
       //etc.
    

    Then $row would be available, but still called $row.

    0 讨论(0)
  • 2021-02-01 08:13

    Consider including a PHP file as if you were copy-pasting the code from the include into the position where the include-statement stands. This means that you inherit the current scope.

    So, in your case, $param is already available in the given template.

    0 讨论(0)
提交回复
热议问题