You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PyPugJS渲染视图模板:寻求替代{% include template_body %}的更优语法

Better Syntax for Dynamic Template Includes in Flask + PyPugJS

Great question! Mixing Jinja2's {% include %} syntax into your PyPugJS templates does feel a bit out of place when you're using Pug's clean, concise syntax elsewhere. Luckily, PyPugJS supports Pug's native dynamic include syntax, which fits much more naturally with your template code.

The Native Pug Solution

Instead of using Jinja2's include tag, you can use Pug's variable interpolation with the include directive. Here's how to update your template:

Modified Template Code

doctype html
html(lang="eng")
  head
    include head.pug
  body
    div.ui.secondary.pointing.menu
      a(href='/').brand.item= brand
      // menu
      include flaskmenu.pug
      include userstatus.pug
    // menu div
    // flash message
    include flashmessage.pug
    // flash message div
    // body
    include #{template_body}
    // body

Why This Works

PyPugJS parses the #{template_body} interpolation and replaces it with the value passed from your Flask view—just like it does with the = brand syntax you're already using. This keeps your template entirely in Pug's syntax, no more mixing Jinja2 tags where they don't belong.

Your Flask View Remains Unchanged

You don't need to modify your route code at all; passing the template_body variable as you're already doing will work perfectly with this new syntax:

@blueprint_home.route('/')
def index():
    user = g.user
    return render_template(
        'index.pug', 
        user=user, 
        template_body='home.pug', 
        flaskmenu=template_show_menu()
    )

Additional Notes

  • Make sure the value of template_body is a valid path relative to your Flask template directory, just like you would with Jinja2's include.
  • If you ever need conditional includes, you can combine this with Pug's control flow syntax for even cleaner code. For example:
    if user.is_admin
      include admin_dashboard.pug
    else
      include #{template_body}
    

This approach keeps your template code consistent, readable, and true to Pug's design philosophy—no more clunky Jinja2 detours!

内容的提问来源于stack exchange,提问作者Peter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:05:13