Django 'include'语句中的多行字符串



我正在尝试使用我的 Django 模板进行 DRY,并有一些与 CSS 混合的代码,用于一个简单的悬停弹出窗口。我想重用代码,但我的弹出窗口的内容将是 HTML,很可能跨越多行。是否可以将多行字符串填充到模板变量中?

我尝试用块和block.super做一些时髦的事情,但这似乎只在扩展(而不是include)时才有效

这是我想做的一个例子。可能吗?

index.html

 <body>
 <h2>My Popup</h2>
 {% include "snippets/popup.html" with class="p" spantext="Hover me" popupdiv="""
  <h2>This is a popup!</h2>
     <ul>
          <li>Something</li>
          <li>Something else</li>
     </ul>
 """
%}
 </body>

snippets/popup.html

 <div class="{{ class }}">
     <span class='pointer'>{{ spantext }}</span>
     <div class="popup">
         {{ popupdiv }}
     </div>
 </div>

我知道在 Django 中不可能有多行模板标签,但是除了将所有我的div html 压缩到一行上并转义任何引号之外,还有什么办法可以解决这个问题吗?

干杯

事实证明,"解析直到另一个模板标签"是我所追求的。 http://www.djangobook.com/en/2.0/chapter09.html

这是我的代码:

tags.py(在templatetags文件夹中)

from django import template
from django.template.loader import get_template
from django.template.base import Node, TemplateSyntaxError
register = template.Library()
class PopupNode(Node):
    def __init__(self, nodelist, class_name, spantext):
        self.nodelist = nodelist
        self.class_name = class_name
        self.spantext = spantext
    def render(self, context):
        popup_html = get_template("ordersystem/snippets/popup.html")
        context.update({
            'class' : self.class_name,
            'spantext' : self.spantext,
            'popupdiv' : self.nodelist.render(context)
        })
        return popup_html.render(context)
@register.tag('popup')
def show_popup(parser, token):
    nodelist = parser.parse(('endpopup',))
    tokens = token.split_contents()
    if len(tokens) != 4:
        raise TemplateSyntaxError("show_popup is in the format 'popup with class=X spantext=Y")
    try:
        context_extras = [t.split("=")[1].strip('"') for t in tokens[2:]]
    except IndexError:
        raise TemplateSyntaxError("show_popup is in the format 'popup with class=X spantext=Y")
    parser.delete_first_token()
    return PopupNode(nodelist, *context_extras)

然后在我的 html 文件中,我可以做:

{% popup with class_name=management spantext=Manage %}
<h2>This is a popup!</h2>
     <ul>
          <li>Something</li>
          <li>Something else</li>
     </ul>
{% endpoup %}

最好的方法应该是在模块中创建带有包含标签的模板标签。

https://docs.djangoproject.com/en/dev/howto/custom-template-tags/

所以想象一下你的是你的模块你的模块,带有文件夹模板标签和文件popup_tag.py

yourModule/
---- views.py
---- models.py
---- templates/
     ---- snippet/
          ---- popup.html
---- templatetags/
     ---- __init__.py
     ---- popup_tag.py

您的popup_tag.py可能如下所示:

from django import template
register = template.Library()
def show_pop_up(class, span_text, popupdiv):
    return {'class': class,
            'span_text': span_text,
            'pop_up_div': pop_up_div}
register.inclusion_tag('snippet/popup.html')(show_popup)

然后,您只需在模板索引中调用您的代码.html。

{% load popup_tag %}
{% show_popup "class" "span_text" "popupdiv" %}

最新更新