Search code examples
phpsmartyassign

Assign php code to smarty template engine


I make a new website for my company and i want to use smarty (v3.1.29) for it. Now the problem is that we store the code for all pages in our database (home, products, downloads, ...). Some pages contains PHP inline functions like:

<?php include("functions.php"); ?>    

<p> Hello <?php echo printWorldInColor(); ?> </p>

In my template (.tpl) file I have a div-section to load the content from our database:

<html>
  <body>
    <div id="content">
      {$content}
    </div>
  </body>
</html>

So my code looks like this afterwards:

<html>
  <body>
    <div id="content">
      <?php include("functions.php"); ?>    

      <p> Hello <?php echo printWorldInColor(); ?> </p>
    </div>
  </body>
</html>

Is there a way that smarty processes the PHP-code before parsing it?

Hint: I dont want to edit my template file. I just want to parse the database content to my content-section of the website.


What i tried:

  • saved database-content into a string and replaced PHP-tags with smarty-PHP-tags, then assign it to the template
  • SmartyBC-Class

Solution

  • You can't do that in Smarty. Also running php code stored in the database sounds like a terrible idea. But if for some reason you have to go on with this nonsense (and considering that you can't use eval), you can try this:

    1. Read the php code from the database.
    2. Save to a temporal php file
    3. Turn on output buffering with ob_start()
    4. include the file you have created
    5. assign the output to a variable with ob_get_clean()
    6. assign the variable to the template

    But if I was you, I would try to do the project in another way.