【问题标题】:Check for a specific url and render jinja2 / html检查特定的 url 并渲染 jinja2 / html
【发布时间】:2021-12-26 20:20:05
【问题描述】:

如何在 html 文件中检查 jinja2 中的特定 URL,然后根据我当前所在的 URL 呈现不同的 html 文件?

例如。

# if {{ request.path == /siteID/ }}
  {% include "file1.html" %}

# if {{ request.path == /siteID/abcde/ }}
  {% include "file2.html" %}
 

我觉得目前的逻辑不太好:

<!-- ..... bunch of html lines .... -->
{% if request.path|length > 8 and request.path.startswith('/siteID/') and request.path[8:].strip('/').split('/')|length == 1 %}
  {% include "file2.html" %}
{% else %}
  {% include "file1.html" %}
{% endif %}
<!-- ..... bunch of html lines .... -->

如果我想在未来做一些事情,我该如何扩展它:

# if {{ request.path == /siteID/abcde/uvwxyz }}
  {% include "file3.html" %}

【问题讨论】:

    标签: html django jinja2


    【解决方案1】:

    由于您想稍后对其进行缩放,因此请不要在模板中执行此操作。将逻辑放入视图函数中,然后将变量传递给存储您要包含的模板名称的渲染函数。例如:

    def the_view(request):
        if request.path == '/siteID/abcde/':
            template = 'file1.html'
        elif request.path == '/siteID/fgh/':
            template = 'file2.html'
        else:
            template = 'file_default.html'
            
        return render(request, 'base.html', {'template_to_include': template})
    

    然后在您的base.html 模板中将此动态导入行放在某处:

    {% include template_to_include %}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-02
      相关资源
      最近更新 更多