简体   繁体   English

如何编写在单引号前添加斜杠的Django模板自定义标签?

[英]How do I write a Django template custom tag that adds a slash before a single quote?

Am I doing this right? 我这样做对吗? (probably not...someone correct? thanks) (可能不是...某人正确吗?谢谢)

@register.filter('addslashes')
@stringfilter
def addslashes(text, arg):
    return text.replace('\'','\\'')


{{ query|addslashes }}

There is a builtin filter with the exact same name: addslashes 有一个名称完全相同的内置过滤器: addslashes

It also escapes double quotes, and double slashes. 它还会转义双引号和双斜杠。 If you only want single quotes, you will have to adapt it and name it differently. 如果只需要单引号,则必须对其进行修改并以其他方式命名。

Here is how the original works: 以下是原始作品的工作方式:

def addslashes(value):
    """
    Adds slashes before quotes. Useful for escaping strings in CSV, for
    example. Less useful for escaping JavaScript; use the ``escapejs``
    filter instead.
    """
    return value.replace('\\', '\\\\').replace('"', '\\"').replace("'", "\\'")
addslashes.is_safe = True
addslashes = stringfilter(addslashes)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM