javascript - 我可以使用 javascript 以 if else 条件呈现 Django 模板的格式吗?
问题描述
我正在使用创建一个 Django 应用程序,我想通过 JS AJAX 方式在 Django 模板中列出不同的产品。我只是想知道如何通过js渲染它-
所以我有两个功能,一个是为每个产品创建模板,如果你注意到我有 if else 条件-
function createTemplate(product) {
return `<div class="col-12 col-lg-3 col-md-6 col-sm-6 mb-45 hot sale">
<div class="single-product">
<div class="single-product__image">
<a class="image-wrap" href="{{product.get_absolute_url}">
<img src="{% if product.image %}
{{ product.image.url }}
{% else %}
{% static 'img/no_image.png' %}
{% endif %}" class="img-fluid" alt="">
</a>
<div class="single-product__floating-icons">
<span class="wishlist">
{% if product.id in wishlist_item_check %}
<a href="javascript:void(0)" id="wishlistalready_${product.id}" data-tippy="Already Exists"
data-tippy-inertia="true" data-tippy-animation="shift-away" data-tippy-delay="50"
data-tippy-arrow="true" data-tippy-theme="sharpborder" data-tippy-placement="left"><i
class="ion-android-favorite" style="color:red"></i></a>
{% endif %}
</span>
</div>
</div>
</div>
</div>`;
}
还有另一个函数来呈现具有特定 id 的 div 中的所有产品(例如她的 id="products>"
function renderProducts(products) {
const template =
products.length === 0
? `
<p>No matching results found.</p>
`
: products.map((product) => createTemplate(product)).join('\n');
$('#products').html(template);
}
最后,我将所有产品呈现在一个 div 中
<div class="row" id="products">
如果我们有更好更简单的方法来做同样的事情,请告诉我。
解决方案
推荐阅读
- vue.js - 用 Vue.js 过滤,获取 Object 的值
- tinymce - 初始化tinymce时重新定义格式样式
- javascript - 将表单输入传递到聊天中
- sql - 将值从 case 表达式插入到表中
- vb.net - SQLITE 仅从文本字段中选择数值
- autodesk-forge - 不与模型交互时的 ClientToWorld 值
- python - 在python中正确编码自相关函数
- json - ConverFrom-JSON 错误:无效的 JSON 基元 || PowerShell PoweBi 嵌入式令牌生成器代码
- angular - NativeScriptException:找不到模块:“crypto”
- linux - 调试(-x)时如何在Shell(/bin/sh)脚本中显示行号?