首页 > 解决方案 > 我可以使用 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">

如果我们有更好更简单的方法来做同样的事情,请告诉我。

标签: javascripthtmldjangoajax

解决方案


推荐阅读