Escape strings for JavaScript using Jinja2?

前端 未结 6 2227
清酒与你
清酒与你 2021-02-18 14:10

How do I escape HTML with Jinja2 so that it can be used as a string in JavaScript (jQuery)?

If I were using Django\'s templating system I could write:

$(         


        
6条回答
  •  春和景丽
    2021-02-18 15:09

    This is a escapejs filter, based on Django's one, that I wrote for use in Jinja2 templates:

    _js_escapes = {
            '\\': '\\u005C',
            '\'': '\\u0027',
            '"': '\\u0022',
            '>': '\\u003E',
            '<': '\\u003C',
            '&': '\\u0026',
            '=': '\\u003D',
            '-': '\\u002D',
            ';': '\\u003B',
            u'\u2028': '\\u2028',
            u'\u2029': '\\u2029'
    }
    # Escape every ASCII character with a value less than 32.
    _js_escapes.update(('%c' % z, '\\u%04X' % z) for z in xrange(32))
    def jinja2_escapejs_filter(value):
            retval = []
            for letter in value:
                    if _js_escapes.has_key(letter):
                            retval.append(_js_escapes[letter])
                    else:
                            retval.append(letter)
    
            return jinja2.Markup("".join(retval))
    JINJA_ENVIRONMENT.filters['escapejs'] = jinja2_escapejs_filter
    

    Example safe usage in a template:

    
    

    When variableName is a str or unicode.

提交回复
热议问题