你能在Flask/Jinja中创建组件来插入不同的模板吗

2024-04-24 04:52:00 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我做了一个非常酷的搜索框布局,我想重用它

例如

<div class='someClass'>
    <input class='fancyInput'>
</div>

有没有可能在其他模板中重用这个代码段,就像我可以扩展到一个模板上一样,但是可以说“导入”一个代码段。就像`{%extend%}的保留

我想有html块,我可以重用,但插入不同的区域,根据网页。在

目前,每次我想使用那块HTML,我必须硬编码。在

下面是一个伪html/jinja示例

片段

^{pr2}$

随便找个地方说吧

<html>
<body>
    <div class='container'><p>Some text!</p></div>
    {% import component fancyInput}
</body>
</html>

呈现的HTML将是

<html>
<body>
    <div class='container'>
        <p>Some text!</p>
    </div>
    <div class='someClass'>
        <input class='fancyInput'>
    </div>
</body>
</html>

Tags: textdiv模板区域inputcontainerhtml代码段
2条回答

使用include在当前模板中包括整个模板文件,docs

文档示例:

{% include 'header.html' %}
    Body
{% include 'footer.html' %}

Jinja2使用宏。元素一旦被定义,就可以调用宏。在

因此,如果在模板中定义宏,例如:

  {% macro newComponent(text) -%}
      <div class='container'><p>{{text}}</p></div>
  {%- endmacro %}

然后可以在任何文件中使用

^{pr2}$

这是指向documentation的链接

也可以对宏执行堆栈溢出post Parameterized reusable blocks with Jinja2 (Flask) templating engine

相关问题 更多 >