在Django模板中渲染之前先剥离JavaScript代码 [英] Strip javascript code before rendering in django templates

查看:68
本文介绍了在Django模板中渲染之前先剥离JavaScript代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

{% if posts %}
    {% for p in posts %}
        {{p|safe}}
    {% endfor %}
{% endif %}

我希望它呈现html而不是javascript,我该怎么办?

I want this to render html but not javascript, what should I do?

推荐答案

django 中没有可以满足您需要的过滤器:剥离javascript并保留html.

There is no filter in django that can do what ou want: strip javascript and leave html.

您可以创建一个自定义模板过滤器来做到这一点:

You can create a custom template filter to do that:

from django import template
from django.template.defaultfilters import stringfilter
from django.utils.safestring import mark_safe
from django.utils.encoding import force_unicode
import re

register = template.Library()

@register.filter
@stringfilter
def stripjs(value):
    stripped = re.sub(r'<script(?:\s[^>]*)?(>(?:.(?!/script>))*</script>|/>)', \
                      '', force_unicode(value), flags=re.S)
    return mark_safe(stripped)

(在何处放置模板过滤器/标签:自定义模板标签和过滤器/代码布局)

(Where to put template filters/tags: Custom template tags and filters/Code layout)

简要说明:

在您的应用程序文件夹中创建一个名为 templatetags 的文件夹.添加一个空文件 __ init __.py (将其作为一个包)和一个模块文件,其中将包含过滤器 my_filters.py .将代码复制到该文件中.

Create a folder named templatetags in your application folder. Add an empty file __init__.py (for it to be a package) and a module file that will contain the filter, my_filters.py. Copy the code in that file.

在模板文件中添加(在首次使用过滤器之前): {%load my_filters%}

In the template file add (before any first use of the filter): {% load my_filters %}

{% if posts %}
    {% for p in posts %}
        {{ p|stripjs }}
    {% endfor %}
{% endif %}

这篇关于在Django模板中渲染之前先剥离JavaScript代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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