Subsections


2. Conditionals


2.1 IF Statement

Of course pyTemple features IF statements. They allow you to display only needed data without of using seperate template or python files.

beispiel.tpl

I{IF FIRST_NAME.len() = 0} don't{ENDIF} know your first name.
I{IF LAST_NAME.len() = 0} don't{ENDIF} know your last name.

beispiel.py

from tplEngine import *
template = TplTemplate('beispiel', 'beispiel.tpl')

template.assign_vars({
    'FIRST_NAME': 'Peter'})
    
print template.get_executed()

To understand this example you have to know, that variables which have not been assigned automatically become an empty string.

Console

$ python beispiel.py
I know your first name.
I don't know your last name.

You may use any kind of expression containing functions and operators inside an IF statement. You have to use ENDIF to end an IF block. Unlike python blocks are in no way bound to indentation which makes it possible to generate nice looking HTML.


2.2 ELSE And ELSEIF

You can attach exactly one ELSE statement to each IF statement. The ELSE Block will be executed if the expression in the IF statement evaluates to False. There is no additional ENDIF required. The ELSE statement contains its own ENDIF so there is only a need for one at the end of the ELSE block.

Additionally you can use ELSEIF to execute a block if the IF expression evaluated to false and the ELSEIF expression evaluates to true. Its ENDIF behaviour is the same as an ELSE's behaviour.

beispiel.tpl

{IF NAME.len() > 0}
    Hello {NAME}
    {IF JOB = "Programmer"}
    for programmers pyTemple provides an easy to use interface.
    {ELSEIF JOB = "Designer"}
    for designers pyTemple is a very simple way to lower working time.
    {ELSE}
    please set a Job!
    {ENDIF}
{ELSE}
    Hello Anonymous
    Please login.
{ENDIF}

beispiel.py

from tplEngine import *
template = TplTemplate('beispiel', 'beispiel.tpl')

template.assign_vars({
    'NAME': 'Peter',
    'JOB': 'Designer'})
    
print template.get_executed()

Console

$ python beispiel.py

    Hello Peter
    for designers pyTemple is a very simple way to lower working time.

See About this document... for information on suggesting changes.