0
<if a == 5 && b < 4>
    one
<else>
    <if a != 5>
        two
    <else>
        <if a == 5 || $b == 5>
            three
         </if>
     </if>
</if>

How i can get from it a some variables:

[0] = "a == 5 && b < 4"
[1] = "one"
[2] = "a != 5"
[3] = "two"
[4] = "a == 5 || $b == 5"
[5] = "three"

Or how would you suggest to make conditions in the template?

2 Answers 2

5

I have nothing against templating systems in general, but why not use plain PHP for this?

<?php if ($a == 5 && ($b < 4)): ?>
    one
<?php elseif ($a != 5): ?>
....

I don't see the benefit of painfully rebuilding the parsing and evaluation logic inside PHP.

If you really need this, I would use Smarty.

Sign up to request clarification or add additional context in comments.

2 Comments

Not to put words in Isis' mouth, but doing it in PHP means it makes the application code vulnerable to silly syntax mistakes and/or breaking the MVC pattern through calls to global PHP functions. Of course, in that case, why not use Smarty or another template engine?
@Victor yeah, but looking at the amount of logic required for this... If it's really needed, I would use Smarty (Update: As you already say)
2

As soon as you start introducing flow control constructs (if, loop... ) to your template language, you lose the ability to apply a template simply by applying a search-and-replace over your variables. You need to start parsing the template to extract the parts that are dependent on a condition, and re-insert them separately should the need happen.

What you will probably end up doing is apply an initial parsing step that turns:

Template "main" :  FOO <if a> BAR </if> QUX

Into:

Template "main" : FOO {temp-if-a} QUX
Template "temp" : BAR

Then, if a is true, you would apply template temp and store it into variable {temp-if-a} while rendering template main. If a is false, you would provide no value for {temp-if-a}.

The other control flow structures can be similarly implemented with this extract-apply independently-replace sequence, including nested ones (just have your template application algorithm work recursively).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.