PyPugJS渲染视图模板:寻求替代{% include template_body %}的更优语法
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_bodyis a valid path relative to your Flask template directory, just like you would with Jinja2'sinclude. - 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

