在Django中替换TextField中的词汇
在Django中,如果你想在TextField里替换一些内容,
[vimeo 123456]
用下面的内容替换
<iframe src="http://player.vimeo.com/video/123456" width="400" height="225" frameborder="0"></iframe>
谢谢你。
2 个回答
0
在你的 TextField
中不要这样做。应该在模板里处理。不过这样的话,你需要解析这个值,所以我建议你写一个简单的模板过滤器:
from django.template.defaultfilters import stringfilter
import re
@stringfilter
def textfieldtourl(value):
#parsing of your '[vimeo <id>]'
#return "http://player.vimeo.com/video/<id>"
然后在模板中使用:
<iframe src="{{ my_object.my_text_field|textfieldtourl }}" width="400" height="225" frameborder="0"></iframe>
这里的 my_object
是你定义 TextField
的对象,my_text_field
是你的 TextField 的名称,而 textfieldtourl
是你定义的过滤器的名称,用来把像 [vimeo 1235]
这样的代码替换成实际的网址。
1
我觉得把HTML放在TextField
里不是个好主意。首先,这样编辑起来会很麻烦(你得写代码把它转回来,这比直接写要难得多);其次,这样会浪费数据库的存储空间,因为要存很多HTML;最后,这样以后修复错误会更困难(比如如果Vimeo改变了他们的URL格式)。
我看到你有两个选择:
1. 视图函数
在你的视图函数里进行这个转换。你的视图函数里会有一行代码,类似于:
context["commentText"] = process_markup(thePost.commentText)
然后,在你的模板文件中,你需要把这个字段标记为safe
,因为你已经过滤过了:
{{ commentText|safe }}
2. 自定义过滤器
在一个自定义过滤器标签里进行这个转换,就像django.contrib.markup
里的restructuredtext
过滤器。这是sebpiq推荐的,可能是更好的选择。
from django.template.defaultfilters import stringfilter
import re
@stringfilter
def mymarkup(value):
return process_markup(value)
然后,在你的模板文件中,你需要调用你的过滤器:
{{ commentText|mymarkup }}
在这两种情况下,你都需要写process_markup(value)
,它的样子可能是这样的:
import re
_TAGS = [
# First, escape anything that might be misinterpreted. Order is important.
(r'&', r'&'),
(r'<', r'<'),
(r'>', r'>'),
(r'"', r'"'),
(r"'", r'''),
# Simple tags
(r'\[b\]', r'<b>'),
(r'\[/b\]', r'</b>'),
# Complex tags with parameters
(r'\[vimeo +(\d+) *\]', r'<iframe src="http://player.vimeo.com/video/\g<1>"'
r' width="400" height="225" frameborder="0"></iframe>'),
]
def process_markup(value):
for pattern, repl in _TAGS:
value = re.sub(pattern, repl, value)
return value
可能还有更好的方法来写这个函数,但你明白我的意思了。