B
B
Bogdan Pasechnik2012-01-05 14:44:37
PHP
Bogdan Pasechnik, 2012-01-05 14:44:37

Safe eval implementation. Need advice?

The task arose to give users the opportunity to write their own templates, which will then be rendered. For obvious reasons, I don’t want to give the opportunity to write just php code, because eval is no longer needed.
Now I'm leaning towards an alternative template language, which I will then parse.
The main requirements of the template are the derivation of variables and iteration through loops. All variables that the template uses are hard-coded and the user does not have access to them. And if he uses in the template those variables that are not defined, they will either be replaced with an empty string, or ignored.
Implemented it like this.
for example, there is a template

<b>{$title}</b><br/>
{foreach $names as $name}<br/>
 {$name}<br/>
{/foreach}<br/>

Using regular expressions, I highlight the code that between foreach I repeat it until the $names array ends and replace it through strtr {$name} with the value of the variable of the current loop iteration. With {$title} too, only without the loop.
But I want a little more options. For example, basic work with if else, getting object properties, the ability to iterate not just a variable, but the result of an object method execution ( {foreach$post->getUsers() as $user} ), calling object methods with parameters.
In general, this is all that I would like. Perhaps someone will have ideas. Since it is long and difficult to implement this functionality in the way that I chose. Maybe there are some libraries that implement similar functionality.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Valery, 2012-01-05
@Akuma

Your example is Smarty 3

C
Cord, 2012-01-08
@Cord

in general, such tasks are solved by the so-called lexical analyzer
en.wikipedia.org/wiki/%D0%9B%D0%B5%D0%BA%D1%81%D0%B8%D1%87%D0%B5%D1%81% D0%BA%D0%B8%D0%B9_%D0%B0%D0%BD%D0%B0%D0%BB%D0%B8%D0%B7#.D0.9B.D0.B5.D0.BA.D1 .81.D0.B8.D1.87.D0.B5.D1.81.D0.BA.D0.B8.D0.B9_.D0.B0.D0.BD.D0.B0.D0.BB.D0.B8 .D0.B7.D0.B0.D1.82.D0.BE.D1.80
read, look.
very useful for broadening one's horizons.
and just writing your own template engine with an analyzer and a compiler is a very difficult and long task.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question