You need to enable JavaScript to run this app. Django模板使用JS跳转URL报错Could not parse the remainder '${id}'求助
优惠活动
大模型
产品
解决方案
定价
更多

Django模板使用JS跳转URL报错Could not parse the remainder '${id}'求助

报错原因

Django 的 {% url %} 属于服务端模板标签,仅在服务端渲染页面时执行,而你代码中的 ${id} 是客户端 JavaScript 的模板变量,服务端渲染阶段 Django 模板引擎无法识别该语法,因此会抛出解析错误。


可行解决方案

方案1:服务端直接渲染完整跳转链接(最推荐)

直接在模板的 onclick 属性中生成完整 URL,无需额外编写 JS 函数处理参数,逻辑最简单无额外兼容问题:

{% for item in store %}
    {% if item.available %}
        <div class="product-container" onclick="window.location.href='{% url 'detail' item.id %}'">
            <img src="{{ item.imageURL }}" alt="Photo" onerror="this.src='http://via.placeholder.com/640x360'"/>
            <h1>{{ item.title }}</h1>
            <h4>RS.{{ item.price|floatformat:2 }}</h4>
        </div>
    {% endif %}
{% endfor %}

该方案可以直接删除你之前写的 redir JS 函数。


方案2:保留redir函数的实现方式

如果业务需要单独封装跳转函数,可以先在服务端生成带占位符的URL模板,JS运行时再替换为真实ID:

<script>
// 服务端渲染带占位符的URL模板
const detailUrlTemplate = "{% url 'detail' 'REPLACE_ID_PLACEHOLDER' %}";
function redir(id){
    // 客户端将占位符替换为真实ID完成拼接
    window.location.href = detailUrlTemplate.replace('REPLACE_ID_PLACEHOLDER', id);
}
</script>

原有模板中的 onclick="redir({{item.id}})" 写法无需修改。


内容的提问来源于stack exchange,提问作者Moeez Ali

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 14:54:05