使用Beautiful Soup将django模板标签添加到模板中

时间:2018-04-03 11:11:54

标签: python django beautifulsoup django-templates

我有一个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>标记传递给要修改的函数,因此这似乎是包含条件字符串的理想位置,因为父级可用&​​amp;模板标记可以添加到<tr><td>;

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'

1 个答案:

答案 0 :(得分:1)

因此,在挖掘了更多内容之后,我发现了insert_beforeinsert_afternew_string来实现我的目标;

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.insert_before(
            soup.new_string('{% if message_url %}')
        )
        row.insert_after(soup.new_string('{% endif %}'))
相关问题