You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django中从过滤器获取HTML并追加到页面出现语法错误如何解决

错误原因

你遇到的Uncaught SyntaxError: Unexpected token '<'报错来自两个核心问题:

  • Django默认会对模板输出内容做HTML转义,你调用的inclusion_tag返回的是完整HTML片段,其中的<、>标签符号会被转义为&lt;、&gt;实体字符,直接放到JS字符串中就会触发语法错误
  • {% recommend_community_first %}是服务端渲染的模板标签,生成的HTML中可能包含换行、双引号等特殊字符,直接包裹在JS字符串中会导致字符串提前闭合、语法解析失败
解决方案

方案1:关闭转义直接输出(适合渲染内容无用户输入的安全场景)

给模板标签调用添加safe过滤器,同时用JS模板字符串包裹避免引号冲突即可:

$('#securedata').append(`{% recommend_community_first request.user.pk | safe %}`);

方案2:预渲染隐藏内容后滚动加载(更稳妥,无JS转义风险)

提前把推荐内容渲染到隐藏容器中,滚动触发时再转移到目标位置:

<!-- 提前预渲染内容到隐藏容器 -->
<div id="recommend_cache" style="display: none;">
    {% recommend_community_first request.user.pk %}
</div>
<span id='securedata'></span>

<script>
window.onscroll = () => {
    if (window.innerHeight + window.scrollY >= document.body.offsetHeight) {
        document.querySelector('body').style.background = 'purple';
        // 仅当目标容器为空时追加,避免重复加载
        if($('#securedata').children().length === 0) {
            $('#securedata').append($('#recommend_cache').html());
        }
    }
    else {
        document.querySelector('body').style.background = 'white';
    }
}
</script>

方案3:滚动时动态请求新内容(适合需要多次加载最新推荐的场景)

如果需要每次滚动都拉取最新的推荐数据,你可以新增接口通过AJAX请求获取内容:

  1. 新增视图函数返回渲染好的推荐HTML
from django.template.loader import render_to_string
from django.http import HttpResponse

def load_recommend(request):
    if not request.user.is_authenticated:
        return HttpResponse('')
    user = request.user
    community = Community.objects.all().order_by('-popularity')[:6]
    posts = Post.objects.filter(community__in=community.values_list('pk', flat=True), video__isnull=True).order_by('-created')
    html = render_to_string('community/recommend_not_recommend.html', {'posts': posts, 'moi': user})
    return HttpResponse(html)
  1. 给上述视图配置对应的URL路由
  2. 调整JS代码发送AJAX请求加载内容:
let isLoading = false;
window.onscroll = () => {
    if (window.innerHeight + window.scrollY >= document.body.offsetHeight) {
        document.querySelector('body').style.background = 'purple';
        if(isLoading) return;
        isLoading = true;
        $.get('你配置的路由地址', function(res) {
            $('#securedata').append(res);
            isLoading = false;
        })
    }
    else {
        document.querySelector('body').style.background = 'white';
    }
}

内容的提问来源于stack exchange,提问作者Thierno Amadou Sow

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 04:27:05