Django'include'语句中的多行字符串 [英] Multi line string in Django 'include' statement
问题描述
我正在尝试对Django模板进行干燥处理,并且将一些代码与CSS混合在一起,以实现简单的悬停弹出式窗口。我想重用代码,但是弹出窗口的内容将是HTML,它们可能会跨越多行。
I'm trying to be DRY with my Django templates, and have some code that I mix with CSS for a simple hover-over popup. I'd like to reuse the code, but the contents of my popup will be HTML that may well span over multiple lines. Is it possible to stuff multi-line strings into a template variable?
我尝试用块和 block.super $ c做一些时髦的事情? $ c>,但这似乎只有在扩展时才起作用(不是
include
)
I tried doing something funky with blocks and block.super
but that only seems to work when extending (not include
)
以下是我的例子d想做。
Here's an example of what I'd like to do. Is it possible?
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压缩到一行并转义任何引号之外?
I know it's not possible to have multi-line template tags in Django, but is there any way round this, other than squashing all my div html onto one line, and escaping any quotes?
干杯
推荐答案
事实证明,解析直到另一个模板标签才是我想要的。 http://www.djangobook.com/en/2.0/chapter09.html
It turns out "Parsing until another template tag" is what I was after. 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文件中,我可以这样做:
Then within my html file I can just do:
{% popup with class_name=management spantext=Manage %}
<h2>This is a popup!</h2>
<ul>
<li>Something</li>
<li>Something else</li>
</ul>
{% endpoup %}
这篇关于Django'include'语句中的多行字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!