簡體   English   中英

如何通過添加來修改Django內容的某些部分<span>,同時保持段落文本的原始格式?</span>

[英]How to modify certain part of Django content by adding <span>, while keeping the original format of paragraph text?

我正在嘗試顯示來自django的文本( content )段落,但是我想向該段落中的特定單詞(與referenceList中預定義單詞匹配的單詞)添加<span class="modify">

這是我的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')? 提前致謝!!

>>> 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>

然后編輯您的視圖代碼。 使用一種形式進行驗證,因為添加跨度時必須將標記標記為安全,否則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 }}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM