Django模板过滤器 - 一行 [英] Django template filter - one line

查看:132
本文介绍了Django模板过滤器 - 一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个Django模板过滤器,将多行结构转换成一个大行。有人实施了吗?
原因是 - 我有一个表单,{{form.as_p}}创建一个多行HTML片段,我想创建一个HTML变量,这是一个HTML片段,但是当我这样做: p>

I'm looking for a Django template filter that turns a multi-line construction into one big line. Has anyone implemented it? The reason is - I have a form, {{form.as_p}} creates a multi-line html fragment, I want to create a javascript variable which is an html fragment, but when I do like this:

var new_div_text = '{{form.as_p}}';

它不工作。原因很明显,在javascript结构中,如

it doesn't work. The reason is obvious, in javascript constructions like

var hello = 'Hello
world';    

无效!

推荐答案

阅读你的用例,看来你只是想删除行。如果你的一个表单标签包含一个字符?糟糕,您的JavaScript现在无效。
Django附带一个过滤器,称为 escapejs ,我们用于这个问题。

Reading your use case, it doesn't appear that you just want to remove lines. What if one of your form labels contains a ' character? Oops, your javascript is now invalid. Django comes with a filter called escapejs which us used for precisely this problem.

使用escapejs,您可以输入:

With escapejs, you would type:

var newDivText = '{{ form.as_p|escapejs }}'

,您不必担心任何角色会摧毁您的JavaScript。

and you won't have to worry about any characters destroying your javascript.

这篇关于Django模板过滤器 - 一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆