【问题标题】:Clean the tags and quotes from a python/django string and make it a valid javascript string清除 python/django 字符串中的标签和引号,使其成为有效的 javascript 字符串
【发布时间】:2015-02-23 17:10:51
【问题描述】:

我的 django 模型中有一个名为 description 的文本字段。我在其中存储了一个字符串,即

<p>Early cricket was at some time or another described as "a club striking a ball 
(like) the ancient games of club-ball, stool-ball, trap-ball, stob-ball".
<sup id="cite_ref-MTG_3-0" class="reference"><a href="http://en.wikipedia.org/wiki/Cricket#cite_note-MTG-3"><span>[</span>3<span>]</span></a></sup> 
Cricket can definitely be traced back to Tudor times in early 16th-century England.
 Written evidence exists of a game known as <em>creag</em> being played by <a title="Edward II of England" href="http://en.wikipedia.org/wiki/Edward_II_of_England">Prince Edward</a>,
 the son of <a title="Edward I of England" href="http://en.wikipedia.org/wiki/Edward_I_of_England">Edward I (Longshanks)</a>, 
at Newenden, Kent in 1301<sup id="cite_ref-4" class="reference"><a href="http://en.wikipedia.org/wiki/Cricket#cite_note-4">
<span>[</span>4<span>]</span></a></sup> and there has been speculation, 
but no evidence, that this was a form of cricket.</p>

我想清理这个字符串,想删除所有的 HTML 标签、双引号和单引号,以便我可以将此字符串分配给一个 javascript 变量。为此,我编写了一个模板标签,它在剥离 al html 标签并用 None 替换所有单引号和双引号后返回字符串。

def clean_text(html_text):
    html=strip_tags(html_text)
    html=html.replace('"','')
    html= html.replace("'",'')
    print html
    return str(html)

但是当我尝试将此字符串分配给 javascript 变量时,我收到错误

SyntaxError: missing ) after argument list
console.log(Early cricket was at some time or another described as a club stri

我也尝试了 toString() 方法,但结果相同。 我试图将它分配给一个变量,但得到了同样的错误

var description = {{object.description|clean_text }}
SyntaxError: missing ; before statement
A number of other words have been suggested as sources for the

register.filter('clean_text',clean_text)

【问题讨论】:

  • 我在后端使用 python/django,前端使用 Javascript

标签: javascript python regex django string


【解决方案1】:

你必须用引号括起来。

var description = "{{object.description|clean_text }}"

但是已经有一个内置过滤器可以完全满足您的需求,escapejs

var description = "{{object.description|escapejs }}"

【讨论】:

  • 谢谢,它可以工作,在此之前我也将它用双引号括起来,但当时它不起作用
猜你喜欢
  • 1970-01-01
  • 2011-06-21
  • 2021-11-01
  • 2019-04-15
  • 2011-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多