【发布时间】:2018-09-12 16:40:57
【问题描述】:
我有一个 django 管理命令,它正在修改模板 & 我想包含一个 django {% if 模板标签以有条件地包含一个块,这样如果 message_url 未定义,则排除以下内容;
<tr>
<td>
If you cannot view this message, please go to the
<a href="{{ message_url }}">
Members Hub
</a>
</td>
</tr>
<a> 标记被传递给要修改的函数,因此这似乎是包含条件字符串的理想位置,因为父级可用并且模板标记可以添加到 <tr> 或 @ 987654326@;
def replace_tag(template, string, template_origin, template_type):
"""
:param template: HTML content
:type: str or unicode
:param string: new string for HTML link
:type: str or unicode
:param template_origin:
:type: str or unicode
:param template_type: MessageType.key of template
:type: str or unicode
:return: modified HTML content
:rtype: unicode
"""
soup = BeautifulSoup(template)
link = find_link(soup, template_type)
if link is not None:
link.string.replace_with(string)
row = link.parent.parent
if '{% if message_url %}' not in row.contents:
row.contents.insert(0, NavigableString('{% if message_url %}'))
if '{% endif %}' not in row.contents:
row.contents.append(NavigableString('{% endif %}'))
# '{% if message_url %}' + row + '{% endif %}'
起初我只是将我的标签作为纯字符串添加到内容中,然后它们被添加到 Tag 内容中,但最终似乎没有成为模板的一部分。
所以我修改它以将字符串添加为NavigableString 对象,但这会导致AttributeError: 'NavigableString' object has no attribute '_is_xml'
【问题讨论】:
-
不管怎样,像这样动态修改模板对我来说似乎非常危险。您不能仅使用模板本身中的条件逻辑来实现相同的目标吗?
-
所以如果我看不到消息,我应该去会员中心。当我没有看到消息时,我怎么知道?
-
@solarissmoke 同意,但由于监管变化,我们必须更新我们发送的电子邮件。所以这些电子邮件模板存储在数据库中,而不是磁盘上。
标签: python django beautifulsoup django-templates