Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 11 of 11
  1. #1
    New Coder
    Join Date
    Oct 2009
    Posts
    78
    Thanks
    1
    Thanked 2 Times in 2 Posts

    Include file in Template

    Ok so i have this Template Engine that parses raw HTML from an body.tpl.php file for example, now i want to send an include() to the body.tpl.php file, the only problem is that the file im trying to include are php files with php code in it.
    But since the function(file_get_contents()) to open the template files can't parse PHP then how am i going to do this?

    Code:
       if(isset($_GET['p']))
       {
       if($funcs->check($_GET['p']) && array_key_exists($_GET['p'],$myarray))
       {
          $name = "./pages/".$_GET['p'].".php";
          $var = implode("", file($name)); 
    
       }
       else
       {
       
         $var = 'This page does not exist!';
    
        }
      }
    
    /*PARSE THE BODY.TPL */
    
    $body = $tpl -> buff_template('body');
    $body_array = array('include_page' => $var);
    echo $tpl -> parse_variables($body, $body_array);
    now when i put {include_page} in the body template it includes any page fine, but it does NOT execute the php inside the included page. it just outputs it as html, i have no clue how i can do it in any other way.

    Any suggestions?

  • #2
    Regular Coder ninnypants's Avatar
    Join Date
    Apr 2008
    Location
    Utah
    Posts
    504
    Thanks
    10
    Thanked 47 Times in 47 Posts
    Are you not able to just use include() or include_once()?

    if not you can probably use exec() to run the php in those files after you've used file get contents thought I wouldn't suggest this solution since it's insecure.

  • #3
    New Coder
    Join Date
    Oct 2009
    Posts
    78
    Thanks
    1
    Thanked 2 Times in 2 Posts
    any method of including(include,include_once etc..) would include it at the top of the page and not centered.
    also i need to define the include in a variable first($var) so i can use it in my array and then use it in my body template.

    and include(); cant be defined in a variable.

    how would i use exec()? i tried a few methods but once i save the page and reload it nothing appears, the page is blank.

  • #4
    New Coder
    Join Date
    Oct 2009
    Posts
    78
    Thanks
    1
    Thanked 2 Times in 2 Posts
    does anyone know what the best way is? exec does not work as it just gives me a blank page.

  • #5
    Senior Coder kbluhm's Avatar
    Join Date
    Apr 2007
    Location
    Philadelphia, PA, USA
    Posts
    1,509
    Thanks
    3
    Thanked 258 Times in 254 Posts
    Your logic is way flawed. $var could be either a path to a file, or a string of text, so how does it know when to embed it and when to include it as a file? I recommend refactoring it to do something like this:
    PHP Code:
    $body = new Template'body' );

    $vars = array(
        
    'text'         => 'This is text',
        
    'include_page' => new Template'content' ),
    );

    $body->assignVars$vars );

    echo 
    $body->render(); 
    Let the constructor decide whether the template is a real file, and then trigger an error or throw an exception if otherwise, but don't hard-code a string of error text.

    This is, of course, pseudo to what you're attempting since I do not know what your template class looks like. It's meant more as a guide and not at all as a copy/paste solution.
    Last edited by kbluhm; 10-22-2009 at 11:26 PM.

  • #6
    New Coder
    Join Date
    Oct 2009
    Posts
    78
    Thanks
    1
    Thanked 2 Times in 2 Posts
    i use it like this in the body.tpl.php file:

    Code:
    $body_array = array('include_page' => $var, 'text' => 'this is some text');
    
    
    
    {include_page} -  to call $var.
    {text} - to output 'this is some text'
    but since file_get_contents gets the raw html it does not execute the php file to include, like it doesnt say: Total accounts created: 1000. it actualy says: echo'Total accounts created: 1000';


    here is my template
    PHP Code:
    <?php

    class template 
    {
     

     
     var 
    $template_dir  './templates/';
     var 
    $file_ext    '.tpl.php';
     var 
    $buffer;
     
     function 
    buff_template ($file
     {
       if( 
    file_exists$this -> template_dir $file $this -> file_ext ) )
       {
         
    $this -> buffer file_get_contents$this -> template_dir $file $this -> file_ext );
         

         return 
    $this -> buffer;
       }
       else
       {
         echo 
    $this -> template_dir $file $this -> file_ext ' does not exist';
       }
     }
     
     function 
    parse_variables($input$array)
     {  
         
    $search preg_match_all('/{.*?}/'$input$matches);
               
         for(
    $i 0$i $search$i++)
         {
           
    $matches[0][$i] = str_replace(array('{''}'), null$matches[0][$i]);
         
         }
         
         foreach(
    $matches[0] as $value)
         {
           
    $input str_replace('{' $value '}'$array[$value], $input);
         }
            
       
         return 
    $input;
     }

    }
    ?>
    Last edited by BinaryX; 10-23-2009 at 12:09 AM.

  • #7
    Senior Coder kbluhm's Avatar
    Join Date
    Apr 2007
    Location
    Philadelphia, PA, USA
    Posts
    1,509
    Thanks
    3
    Thanked 258 Times in 254 Posts
    I think what ninnypants meant was eval(), not exec().
    PHP Code:
    $source preg_replace'/\<\?(php)?(.*)\?\>/Usie''eval( \'\2\' )'$source ); 
    Thing is, this can be unpredictable as strings can potentially contain PHP open/close tags not to be used in parsing. It's not a huge threat to happen often, but I wouldn't want to rely on eval().
    Last edited by kbluhm; 10-23-2009 at 07:13 AM.

  • #8
    New Coder
    Join Date
    Oct 2009
    Posts
    78
    Thanks
    1
    Thanked 2 Times in 2 Posts
    i really have no idea where to put this, i know somewhere in the template file, but where?

  • #9
    Senior Coder kbluhm's Avatar
    Join Date
    Apr 2007
    Location
    Philadelphia, PA, USA
    Posts
    1,509
    Thanks
    3
    Thanked 258 Times in 254 Posts
    Ok, it seems a bit useless to use pseudo variables if you want to be able to execute PHP code anyhow, but here's a refactored Template class.

    It's not using eval() because all we really have to do is include and buffer the requested template, then just swap all pseudo-variables with their assigned values... which is, once again, a bit redundant and will incur extra overhead in order to simply replace <?php echo $this->content ?> with {content}.

    We'll use the __toString() magic method to allow us to echo a template object as a string:

    Template.php
    PHP Code:
    <?php

    class Template
    {

        
    /* - - - - - - - - - -
         * Properties
         */

        
    protected
            
    $template  NULL,
            
    $vars      = array();

        protected static
            
    $path      NULL,
            
    $extension NULL;

        
    /* - - - - - - - - - -
         * Constructor
         */

        
    public function __construct$template )
        {

            
    // Default path
            
    if ( ! is_dirself::$path ) )
            {
                
    self::$path dirname__FILE__ ) . DIRECTORY_SEPARATOR;
            }

            
    // Default extension
            
    if ( NULL === self::$extension )
            {
                
    self::$extension '.tpl.php';
            }

            
    // Are we loading a template?
            
    if ( NULL !== $template )
            {
                
    $templatePath realpathself::$path $template self::$extension );
                if ( ! 
    is_file$templatePath ) )
                {
                    throw new 
    Exception'The template "' $template self::$extension '" could not be located' );
                }
                
    $this->template $templatePath;
            }

        }

        
    /* - - - - - - - - - -
         * Render the output
         */

        
    public function render()
        {

            
    // Capture the PHP output
            
    ob_start();
            include 
    $this->template;
            
    $source ob_get_clean();

            
    // Replace defined pseudo variables
            
    if ( ! empty( $this->vars ) )
            {
                
    // This expression allows for the intelligent replacement of messy pseudo vars
                // It will leave all other curly braces alone (ie: embedded javascript, etc)
                // Examples:
                // -> {var}
                // -> { var }
                // -> {      var  }
                // -> {
                //        var
                //    }
                
    preg_match_all'/\{\s*(' implode'|'array_keys$this->vars ) ) . ')\s*\}/s'$source$pseudo );
                
    // Replace defined pseudo variables
                
    foreach ( $this->vars as $name => $value )
                {
                    if ( 
    FALSE !== ( $i array_search$name$pseudo[1] ) ) )
                    {
                        
    $source str_replace$pseudo[0][$i], $value$source );
                    }
                }
            }

            
    // Send it on it's way
            
    return $source;

        }

        
    /* - - - - - - - - - -
         * Setters / Getters
         */

        
    public static function setPath$path )
        {
            
    $templatePath realpath$path );
            if ( ! 
    is_dir$templatePath ) )
            {
                throw new 
    Exception'The path "' $path '" does not exist' );
            }
            
    self::$path $templatePath DIRECTORY_SEPARATOR;
        }

        public static function 
    setExtension$extension )
        {
            
    self::$extension '.' trim$extension'.' );
        }

        
    /* - - - - - - - - - -
         * Magic Methods
         */

        
    public function __toString()
        {
            return ( string ) 
    $this->render();
        }

        public function 
    __call$name$params )
        {
            return isset( 
    $this->vars[$name] ) ? $this->vars[$name] : array_shift$params );
        }

        public function 
    __get$name )
        {
            return isset( 
    $this->vars[$name] ) ? $this->vars[$name] : NULL;
        }

        public function 
    __set$name$value )
        {
            return 
    $this->vars[$name] = $value;
        }

        public function 
    __isset$name )
        {
            return isset( 
    $this->vars[$name] );
        }

        public function 
    __unset$name )
        {
            if ( isset( 
    $this->vars[$name] ) )
            {
                unset( 
    $this->vars[$name] );
            }
        }

    }
    And here are some test files:

    index.php
    PHP Code:
    <?php

    require './Template.php';

    // Create our main body template
    $body = new Template'body' );
    $body->title 'This is the custom title';

    // Create a content template
    $content = new Template'content' );
    $content->date date'Y-m-d H:i:s' );

    // assign the content to the main body
    $body->content $content;

    // Send it on it's way
    echo $body;
    body.tpl.php
    PHP Code:
    <html>
        <head>
            <title>
                <?php echo $this->title'This is the default title if no title is specified' ?>
            </title>
        </head>
        <body>
            {content}
        </body>
    </html>
    content.tpl.php
    PHP Code:
    <p>This is an included file.</p>

    <
    p>{ date }</p
    And here is the rendered output:
    Code:
    <html>
    	<head>
    		<title>
    			This is the custom title		</title>
    	</head>
    	<body>
    		<p>This is an included file.</p>
    
    <p>2009-10-23 08:59:53</p>
    	</body>
    
    </html>
    You should be able to follow the code in index.php to understand what the template class is allowed to do.

    To change the path or extension, simply call either of these static methods prior to calling new Template(). These can be called anywhere, so you can use one template folder, then further down in your code, change the folder or extension.
    PHP Code:
    Template::setPath'/path/to/templates/folder' );
    Template::setExtension'tpl.php' ); 
    Also note that since we are just including what amounts to text files, the extension could be anything and does not necessarily have to end with .php.

    And once again, this is all just a basic example.
    Last edited by kbluhm; 10-24-2009 at 05:52 AM.

  • #10
    New Coder
    Join Date
    Oct 2009
    Posts
    78
    Thanks
    1
    Thanked 2 Times in 2 Posts
    Thank you so much! this is way better, however the php page's im trying to include still dont get executed, it just gets echoed as raw html.

    Code:
    <?php
    $starttime = microtime();
    $startarray = explode(" ", $starttime);
    $starttime = $startarray[1] + $startarray[0];
    
    require './Template.php';
    require './global.php';
    $funcs = new Funcs();
    # BODY TEMPLATE
    Template::setPath( './Templates/' );
    Template::setExtension( '.tpl.php' );  
    $body = new Template( 'body' );
    $content = new Template( 'content' );
    $content->date = date( 'Y-m-d H:i:s' );
    $body->content = $content;
    
    
    #INCLUDE SCRIPT
    $myarray = array("register" => 0, "register_process" => 1, "login" => 2, "logout" => 3, 'players' => 4, 'forgot_pass' => 5, "user" => 6, "user_ranks" => 7,"GM" => 8,"clan" => 9,"clan_ranks" => 10,"test" => 11);
       if(isset($_GET['p']))
       {
       if($funcs->check($_GET['p']) && array_key_exists($_GET['p'],$myarray))
       {
          $name = "./pages/".$_GET['p'].".php";
          $var = implode("", file($name)); 
          $body->include = $var;
       }
       else
       {
       
         $var = "This page does not exist!";
         $body->include = $var;
        }
      }
      
      $connection = $funcs->dbConnect();
      $query = odbc_exec($connection,"SELECT TOP 1 id,n_title,n_text,date FROM X_News ORDER BY date ASC");
      while($row = odbc_fetch_array($query))
      {
      $body->n_id = $row['id'];
      $body->n_title = $row['n_title'];
      $body->n_text = $row['n_text'];
      $body->n_date = $row['date'];
    
      } 
      odbc_close($connection);   
    
    $endtime = microtime();
    $endarray = explode(" ", $endtime);
    $endtime = $endarray[1] + $endarray[0];
    $totaltime = $endtime - $starttime;
    $totaltime = round($totaltime,5);
    $body->time = $totaltime;
    
    
    
    
    
    // Send it on it's way
    echo $body;
    
    
    
    ?>

  • #11
    New Coder
    Join Date
    Oct 2009
    Posts
    78
    Thanks
    1
    Thanked 2 Times in 2 Posts
    oh i had to create a new template, thank you so much for ur help!


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •