In Jinja2, how can I use macros in combination with block tags?

后端 未结 1 1057
孤街浪徒
孤街浪徒 2021-02-14 12:08

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,

1条回答
  •  别那么骄傲
    2021-02-14 13:00

    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:

    
    
      {{ title }} | Site.com
      ....
      {% block content %}{% endblock content %}
      ....
    
    

    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.

    0 讨论(0)
提交回复
热议问题