如何通过添加<span>来修改Django内容的某些部分,同时保留段落文本的原始格式?

时间:2016-02-12 02:25:57

标签: python html css django django-templates

我正在尝试从django显示一段文字(content),但我想将<span class="modify">添加到特定的字词(与referenceList中的预定义字词匹配)在段落中。

这是我的view.py:

def post_content(request, id=None):
    instance = get_object_or_404(post, id=id)
    content = instance.content.split()
    referenceList = ["customer","sales","service","management"]
    context = {
        "title": instance.title,
        "instance": instance,
        "content": content,
        "referenceList": referenceList
    }
    return render(request,"get_post_content.html",context)

这是我的get_post_content.html:

<!--DOCTYPE html-->
<html>
<style type="text/css">
    .modify{
        color: blue;
    }
</style>
<body>
    <h1>{{ instance.title }}</h1>
    {{ instance.author }}<br/>
    <pre class="postContent">
        {% for obj in content %} 
                {% if obj in referenceList %}
                    <span class="modify">{{ obj }}</span>
                {% else %}
                    {{ obj }}
                {% endif %}
        {% endfor %}
    </pre>  
</body> 
</html>

这能够区分单词并更改为我想要的css,但它只是通过并显示字符串列表和所有空格并且'\ n'丢失。有没有办法保持文本的原始格式(保留空格和'\ n')? 在此先感谢!!

1 个答案:

答案 0 :(得分:0)

>>> def add_span(arg)
>>>     return  '<span class="modify">  %s </span>'%arg.string[arg.regs[0][0]:arg.regs[0][1]] 
>>> import re
>>> r = re.compile("foo|baz")
>>> content = "Once upon a time foo met baz"
>>> print r.sub(add_span,content)
Once upon a time <span class="modify">  foo </span> met <span class="modify">  baz </span>

然后编辑您的视图代码。使用表单进行验证,因为当您添加span时,您必须将标记标记为安全,否则django将逃避它:

    import re
    from django import forms

    def add_span(arg)
        return  '<span class="modify">  %s </span>'%arg.string[arg.regs[0][0]:arg.regs[0][1]] 
    r = re.compile("customer|sales|service|management")

    class ValidateRefList(Form):

       content = forms.CharField()

       def save(self):
          return r.sub(add_span,self.cleaned_data['content'])

    def post_content(request, id=None):
        instance = get_object_or_404(post, id=id)
        f = ValidateRefList({'content':instance.content})
        if f.is_valid():
            fixed_content = f.save()
        else:
            # do something else
        context = {
            "title": instance.title,
            "instance": instance,
            "content": fixed_content   
        }
        return render(request,"get_post_content.html",context)

最后,在您的模板中,只需:

{{ content|safe }}