Bottle uses its own little template engine by default. You can use a template by calling template(template_name, **template_arguments)
and returning the result.
@route('/hello/:name') def hello(name): return template('hello_template', username=name)
This will load the template ‘hello_template.tpl’ with the ‘username’ variable set to the URL :name part and return the result as a string.
The hello_template.tpl file could look like this:
<h1>Hello {{username}}</h1> <p>How are you?</p>
The list bottle.TEMPLATE_PATH
is used to map template names to actual files. By default, this list contains ['./%s.tpl', './views/%.tpl']
The template syntax is a very thin layer around the python language. It’s main purpose is to provide the correct indention of blocks, so you can format your template without worrying about indentions. Here is the complete syntax:
%...
starts a line of python code. You don’t have to worry about indentions. Bottle handles that for you.%end
closes a Python block opened by %if ...
, %for ...
or other block statements. Explicitly closing of blocks is required.{{...}}
prints the result of the included python statement.%include template_name optional_arguments
allows you to include other templates.Example:
%header = 'Test Template' %items = [1,2,3,'fly'] %include http_header title=header, use_js=['jquery.js','default.js'] <h1>{{header.title()}}</h1> <ul> %for item in items: <li> %if isinstance(item, int): Zahl: {{item}} %else: %try: Other type: ({{type(item).__name__}}) {{repr(item)}} %except: Error: Item has no string representation. %end try-block (yes, you may add comments here) %end </li> %end </ul> %include http_foother