⌘BABAKOV.NET Let's code!
100% [dark] [ru]

Python Bottle Guide (Translation) Part 6 - Templates (on Templates)

In the previous part (Python Bottle Guide (Translation) Part 5 - Request Data (data in the request)) we considered the main aspects related to the data transmitted in requests, in this part we will briefly consider the use of templates.

Bottle has a fast and powerful built-in template mechanism called SimpleTemplate Engine. To render a template, you can use the template() function or the view() decorator. All you need to do is provide the template name and the variables you want to pass to the template as arguments. Here is a simple example of how to access a template:

@route(\'/hello\')
@route(\'/hello/<name>\')
def hello(name=\'World\'):
    return template(\'hello_template\', name=name)



This code will load the template file hello_template.tpl and display it with the set variable name. Bottle will look for templates in the folder ./views/ or in any folder specified in the list bottle.TEMPLATE_PATH.
The view() decorator allows you to return a dictionary of template variables instead of calling template():

@route(\'/hello\')
@route(\'/hello/<name>\')
@view(\'hello_template\')
def hello(name=\'World\'):
    return dict(name=name)



Syntax (Syntax)


Template syntax is a very small wrapper around the Python language. Its main goal is to provide proper indentation of blocks, so you can format the template without worrying about indentation. Full syntax description: SimpleTemplate Engine (in English, possibly to be translated in the future. :) )

Here is an example template:

%if name == \'Мир\':
    <h1>Привет {{name}}!</h1>
    <p>Это тест.</p>
%else:
    <h1>Привет {{name.title()}}!</h1>
    <p>Как дела?</p>
%end



Caching (Caching)


Templates are cached in memory after compilation. Changes made to template files will not affect until you clear the template cache. To do this, you need to call bottle.TEMPLATES.clear(). Caching is disabled in debug mode.

Continuation follows…

Comments (0)

No comments yet.

Leave a comment
Comment
Images (up to 5 MB)
Your comment will appear after moderation.