Page 1 of 1

Looping problem with templates

Posted: Fri Nov 14, 2008 12:33 pm
by TeNDoLLA
I have some problems figuring out how to solve a template rendering problem with php.

Lets say I have for example in template something like this. I fetch data from db and I need to loop the part between comments for unknown times depending on the data fetched from db. From db eg. each row has three values (label, desc and price).

Code: Select all

 <head><title>[:title:]</title></head><body><h1>[:heading:]</h1><table><!-- part that will be looped starts --><tr>    <td>        [:label:] - [:desc:] - [:price:]</br>     </td></tr><!-- looped part ends --></table></body></html> 
So what would be the best way to implement this looping with php? Or is there any good ways? The reason why php is not allowed in templates at all is that all of the users who will be editing templates later does not know any php or mysql.

Re: Looping problem with templates

Posted: Fri Nov 14, 2008 12:48 pm
by Hannes2k
Hi,
my solution would be:
create a new template with the content:

Code: Select all

 
<tr>
    <td>
        [:label:] - [:desc:] - [:price:]</br>
    </td>
</tr>
That's would be one row in the table.

Your old template would looks like:

Code: Select all

 
<head><title>[:title:]</title></head>
<body>
<h1>[:heading:]</h1>
<table>
<!-- part that will be looped starts -->
[:table_content:]
<!-- looped part ends -->
</table>
</body>
</html>
In PHP you read the template for the table row, you loop through your database and creates the correct table_content data.

Another way would be to mark it as a table/loop for database:

Code: Select all

 
<head><title>[:title:]</title></head>
<body>
<h1>[:heading:]</h1>
<table>
<!-- part that will be looped starts -->
{begin_loop_table}
<tr>
    <td>
        [:label:] - [:desc:] - [:price:]</br>
    </td>
</tr>
{end_loop_table}
<!-- looped part ends -->
</table>
</body>
</html>
Your template engine have to get the code between {begin_loop_table} and {end_loop_table} and have to use it as a template for the rows of your table.

Re: Looping problem with templates

Posted: Sat Nov 15, 2008 10:08 am
by TeNDoLLA
Okey so far I have gotten in to that point where I have the looped data with values in a variable. Now where I am stuck is that how do I replace this block between the {start_loop} and {end_loop} tags in the template with the new content with values. I couldn't get it working with replace functions. When rendering the template to be ready to be dislpayed I need to do this replace but I wasn't able to replace multiline block with multiline content variable with any replace function. Is it possible?

Re: Looping problem with templates

Posted: Sat Nov 15, 2008 10:46 am
by TeNDoLLA
Solved... was just wrong pattern in regexp.