Django inclusion tag for Kay framework

Django inclusion tag helps you when you need to repeat the same HTML block for several times or keeping your design consistent site-wide.
How can you do the same in Kay framework? Is there such an option?
Well, first of all, you need to search in the right place, like the docs say:
Kay uses Jinja2 for rendering HTML templates.
So let's check the Jinja2 Template Designer Documentation. This is where the solution can be found: Macros
Macros
Macros are comparable with functions in regular programming languages. They are useful to put often used idioms into reusable functions to not repeat yourself.
This is exactly what we were searching for.
Lets take the polls results example from Django docs and transform it in a Kay/Jinja2 macro:
Django
- # polls.templatetags.poll_tags
- from django import template
- register = template.Library()
-
- @register.inclusion_tag('results.html')
- def show_results(poll):
- choices = poll.choice_set.all()
- return {'choices': choices}
-
- # templates/polls/results.html
- <ul>
- {% for choice in choices %}
- <li> {{ choice }} </li>
- {% endfor %}
- </ul>
-
- # templates/polls/view_poll.html
- {% load poll_tags %}
- {% show_results poll %}
Kay framework
- # templates/polls/macros.html
- {% macro show_results(poll) %}
- <ul>
- {% for choice in poll.choices_set.fetch(1000) %}
- <li> {{ choice }} </li>
- {% endfor %}
- </ul>
- {% endmacro %}
-
- # templates/polls/view_poll.html
- {% from "polls/macros.html" import show_results %}
- {{ show_results(poll) }}
First obvious difference, in Kay, the code doesn't stay in a separate .py file, but in an .html one which needs to be imported directly in the template where it is being used.
Unfortunately, if you need to handle the arguments in some special way, you are limited by normal template syntax only and this might not be the right solution.
Special macro + call
Jinja also comes with something extra by using macro + call together. This is like calling a macro inside another macro and it is useful as replacement for loops.
- {% macro dump_users(users) %}
- <ul>
- {% for user in users %}
- <li><p>{{ user.username|e }}</p>{{ caller(user) }}</li>
- {% endfor %}
- </ul>
- {% endmacro %}
-
- {% call(user) dump_users(list_of_user) %}
- <dl>
- <dl>Realname</dl>
- <dd>{{ user.realname|e }}</dd>
- <dl>Description</dl>
- <dd>{{ user.description }}</dd>
- </dl>
- {% endcall %}
Categories: GAE Kay Framework



Leave a Comment :
Leave a Comment