用星号加粗文字

时间:2016-09-27 12:24:39

标签: python django

在我的Django项目中,如果文本的开头和结尾有星号*,我希望将文本设为粗体,这与Stack Overflow中的相同功能相同。虽然我将**转换为<b>,但由于输出转义,它变为&lt;b&gt;。实现这一目标的正确方法是什么?

模板文件包含{{ anidea.description|format_text}}

format_text是自定义模板过滤器

代码..

from django import template
from django.utils.safestring import mark_safe


register = template.Library()

@register.filter(name='format_text')
def custom_formating(value):
   for word in value.split():    

     start = word[:2]
     end = word[-2:]

     if start == '**' and end == '**':
        word = word[2:-2]        
        word = '<b>' +word+ '</b>'
        mark_safe(word)    


  return value

2 个答案:

答案 0 :(得分:0)

如果您想要所有降价功能的完整套件,请使用现有的降价库。

如果您只是想&lt; b&gt;要直接打印到没有转义的源代码,请使用

 {{ some_var|safe }}

答案 1 :(得分:0)

我是按照以下方式做到的。

views.py

i.description = i.description.split()  #use of split()

模板文件(format_text为custom template filter

{% for text in anidea.description %}
     {{ text|format_text }}
{% endfor %} 

过滤

@register.filter(name='format_text')
def custom_formating(value):
 start = value[:2]
 end = value[-2:]

 if start == '**' and end == '**':
     value = value[2:-2]        
     value = '<b>' +value+ '</b>'
     return mark_safe(value) 
 else:
     return value

通过这种方式,我可以实现输出转义以进行描述和所需的文本格式化。

相关问题