Jump to content

How to Insert PHP Control Structure into a Template Generator


Recommended Posts

BACKGROUND: I have an HTML template that contains a variety of template variables designated by the following pair of delimiters %varname%.  In most cases there is a one-to-one correspondence between the values of a set of PHP variables gathered on a PHP processing page and the template variables found on the HTML template.  The routine for populating the template variables with values is captured in the following code snippet of a very simple PHP class designed for generating templates.

        function replace_tags($tags) {
            if (sizeof($tags) > 0) {
                foreach ($tags as $tag => $data) {
                    $replace = '%\%' . $tag . '\%%';
                    $data = (file_exists($data)) ? join("", file($data)) : $data;
                    $this->page = preg_replace($replace, $data, $this->page);
            } else {
                die("No tags designated for replacement.");

The PROBLEM:  My difficulty arises when I seek to populate one of the sets of template variables whose number of sets is not clearly known until the template is generated.  Within the template HTML code for a single set of three variables is set aside.  Ostensibly, this same set of variables could be repeated five different times, with each time carrying a different set of values.

PROBLEM RESOLUTION:   As each set of PHP data is numerically encoded there is no confusion about which data goes with each set.  And, since the HTML code for each set of data is identical across sets it appears to be a relatively easy task to populate the template variables of the relevant  set repeatedly with different data from different PHP variable sets.

imagine myself breaking the HTML code into three parts:  the part that comes before the dynamically generated HTML; the part that generates the dynamic HTML code; and the part that that comes after the dynamically generated HTML. 

Can anyone suggest an alternative strategy?  One, for example, that would simply allow me to insert the dynamically generated HTML on the fly?



Link to comment
Share on other sites


It would be easier to address this if you could show examples of your template and maybe the data.

It's OK.  I have figured out a solution.  I will generate the variable HTML code dynamically outside the template and then insert the result as the value of an HTML template variable that serves as a placeholder for the dynamically generated content within the template.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Create New...