How do I create a macro, using Bottle's SimpleTemplate engine, that will be available in several templates?
I need to format a link in certain places of my Bottle application. Previously all of the links were in one SimpleTemplate file, and I defined a macro that looks like this:
%def mylink(obj):
<a class="mylink" href="{{ get_url('view', id=obj.id) }}">{{ obj.title }}</a>
%end
Wherever I needed to format a link to an obj
, I used:
%mylink(some_obj)
Now I need to use format such links in several templates. I moved the template definition to a separate file called macros.html
, then tried %include
ing this file into the templates where I need the macro:
<!-- macros.html -->
%def mylink(obj):
<a class="mylink" href="{{ get_url('view', id=obj.id) }}">{{ obj.title }}</a>
%end
<!-- somepage.html -->
%include macros
...
%mylink(some_obj)
...
However, Bottle cannot resolve the name mylink
in such a layout.
I understand I can do this:
<!-- mylink.html -->
<a class="mylink" href="{{ get_url('view', id=obj.id) }}">{{ obj.title }}</a>
<!-- somepage.html -->
...
%include mylink obj=some_obj
...
However, I'm reluctant to do this, as I feel this isn't very fast (I have many links to format on any given page).
Am I miss开发者_StackOverflow中文版ing some other options?
The %include
statement renderes the included template immediately.
Myby you can solve this using the %rebase
command, putting your macro into the base template.
精彩评论