Using multiple web2py templates

Okay, today we are going to talk about templates and multiple views on web2py.

This tip will be valid for you who want dynamic templates in your app, where you can easily change it whenever you want, passing parameters in the appconfig or something like that.

The idea is very basic, you have a repository of templates inside views where you will put your layouts inside, for example temp01, temp02 ...

We will also take the opportunity to learn a little more about the web2py (W2P) template engine (TE) called yatl in the new py4web.

Come on...

The W2P TE allows us to inherit views and inclusions through the reserved words extend and include respectively.

But if they are reserved words, aren't they python code?
Exactly, extend and include and also block are not python code, so they are executed before any python code in our view.

That is, the code below will never work.
{{if condition:}}
{{extend 'temp01.html'}}
{{else:}}
{{extend 'temp02.html}}

Not even that.
{{from gluon.contrib.appconfig import AppConfig
myconf = AppConfig ()}}
{{extend myconf ("app.template")}}

But the one below does.
{{extend 'temp01.html' if condition else 'temp02.html'}}

That's because regular expressions within reserved words are possible, don't ask me why.

So, then, when we do {{extend var_template}} and try to compile our app it generates an error, because var_template is not recognized in the TE. But that doesn't stop the raw code (html) from being executed.

So how can we solve this problem?
Simple, we can define a response.template within our db.py file, like this:

response.template = 'templates / temp01 / layout.html' # import temp01 layout

And within our view we use:
{{extend response.template}}

As response is executed in the W2P environment, it is executed when the template engine is compiled.

To be continued....

References:
https://groups.google.com/forum/#!searchin/web2py/{{extend$20template}}|sort:relevance/web2py/AQDArfPGuFI/-fViEMoWneIJ

Comentários

Postagens mais visitadas deste blog

Configurar o web2py no Apache e Ubuntu LTS

Usando multiplos templates web2py

Placeholders em Campos de SQLFORM