开发者

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

开发者 https://www.devze.com 2022-12-18 20:33 出处:网络
Am I doing this right? (probably not...someone correct? thanks) @register.filter(\'addslashes\') @stringfilter

Am I doing this right? (probably not...someone correct? thanks)

@register.filter('addslashes')
@stringfilter
def addslashes(text, arg):
    return tex开发者_如何学运维t.replace('\'','\\'')


{{ query|addslashes }}


There is a builtin filter with the exact same name: 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)
0

精彩评论

暂无评论...
验证码 换一张
取 消