Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP templating with str_replace?

Tags:

php

templates

I think the basic principle of a PHP templating system is string replacing, right? So can I just use a string to hold my html template code like

$str_template = "<html><head><title>{the_title}</title><body>{the_content}</body></html>"

and in the following code simply do a str_replace to push the data into my template variable like

str_replace( $str_template, '{the_title}', $some_runtime_generated_title );
str_replace( $str_template, '{the_content}', $some_runtime_generated_content );

then at last

echo $str_template; 

Will this hopefully make the whole variable passing process a bit faster? I know this could be a weird question but has anybody tried it?

like image 971
Shawn Avatar asked Jan 25 '09 08:01

Shawn


People also ask

How to replace string with another string PHP?

The str_replace() function replaces some characters with some other characters in a string. This function works by the following rules: If the string to be searched is an array, it returns an array. If the string to be searched is an array, find and replace is performed with every array element.

Is PHP a templating language?

He wasn't opposed to using C to handle back-end business logic but wanted a better way to generate dynamic HTML for the front end. PHP was originally designed as a templating language, but adopted more features over time and eventually became a full programming language in its own right.

Is PHP a templating engine?

Every modern PHP Web application framework employs some kind of templating engine. Most of them use plain PHP by default (including Symfony 1. x, Zend Framework and CakePHP), but many standalone libraries can be plugged into your favorite framework or custom application.

How do you use templates in PHP explain?

A PHP template engine is a way of outputting PHP in your HTML without using PHP syntax or PHP tags. It's supposed to be used by having a PHP class that will send your HTML the variables you want to display, and the HTML simply displays this data.


1 Answers

Yes, that is the basic idea behind a templating system. You could further abstract it, let an other method add the brackets for example.

You could also use arrays with str_replace and thus do many more replaces with one function call like this

str_replace(array('{the_title}', '{the_content}'), array($title, $content), $str_template);

The system I work with is Spoon Library, their templating system is pretty rock solid, including compiled templates, which are a huge performance gain.

like image 95
Javache Avatar answered Oct 19 '22 22:10

Javache