【问题标题】:Conditionally insert a piece of Django template with HTML code into my template using Javascript使用 Javascript 有条件地将一段带有 HTML 代码的 Django 模板插入到我的模板中
【发布时间】:2021-04-17 12:14:11
【问题描述】:

我正在尝试使用 Django 创建一个模板,以用于我项目中的所有页面。所有页面都显示类似的表格,这使得它更容易,但其中一些需要额外的一两次检查。所以在写这个千篇一律的模板时,如果它是一种类型的页面,我想要这段代码:


    {% if not package_check %}
    <p style="color:red">Package not found, so script did not run. Install package and try again</p>

    {% elif count|length %}
     <!-- rest of html template -->
    {% endif %}

否则,我想要这段代码:


    {% if count|length %}
    <!-- rest of html -->
    {% endif | length %}

由于它们非常相似,我想知道是否有可能(以及如何做到)在加载页面时将其插入到带有 Javascript 的 HTML 中,并使其测试模板标签中的 Django 变量。

【问题讨论】:

    标签: javascript html django django-templates


    【解决方案1】:

    没什么好理解的。尽量写清楚。

    【讨论】:

      【解决方案2】:

      您想插入一个新模板或从 javascript 创建一个新的 html 元素

      如果你想包含新模板

      你可以这样做

      {% if not package_check %}
          <p style="color:red">Package not found, so script did not run. Install package and try again</p>
      
          {% elif count|length %}
           <!-- rest of html template -->
          {% include 'youranothertemplate.html' %}
          {% endif %}
      

      从 javascript 创建新元素

      const newElement = document.createElement("h1")
      newElement.innerText = "Hai"
      document.getElementById("new").append(newElement)
      <div id="new">
      
      </div>

      【讨论】:

      • 根据请求页面,我希望我的模板加载原始帖子中的第一个脚本或第二个脚本,模板的其余部分应该是相同的。我试图避免使用多个模板,因为 99% 的代码是相同的
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-18
      • 2016-04-10
      • 2021-03-22
      • 2021-09-03
      • 2023-03-13
      • 1970-01-01
      • 2019-03-07
      相关资源
      最近更新 更多