Skip to content Skip to sidebar Skip to footer

In Jinja2, How Can I Use Macros In Combination With Block Tags?

I'm a front end developer, and I've been trying to get a hang on using Jinja2 effectively. I want to tweak a current site so it has multiple base templates using inheritance, it fu

Solution 1:

Blocks are only definable at a template's top level. If you extend a template, any values set in the child template using a set tag will be accessible from the template it is extending. For example, if you have a template named layout.html:

<!DOCTYPE HTMLPUBLIC"-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd"><html><title>{{ title }} | Site.com</title>
  ....
  {% block content %}{% endblock content %}
  ....
</html>

And you have this child template, index.html:

{% extends "layout.html" %}
{% set title = 'Homepage' %}
{% block content %}
(html code here)
{% endblock content %}

Then the reference to title in the parent would resolve to 'Homepage'. You can do this with any type of variable. For what you're doing, I don't think there is any need for macros - if you take advantage of this feature and place blocks well, you will be able to do pretty much everything you need to do as far as layouts are concerned. I would look at some of the templates used by Plurk Solace, which is written by one of the Jinja2 authors, if you want to get a good idea of when to use various features of Jinja2.

Post a Comment for "In Jinja2, How Can I Use Macros In Combination With Block Tags?"