【问题标题】:How to dynamically render Vue.js directives in custom Django template tags如何在自定义 Django 模板标签中动态呈现 Vue.js 指令
【发布时间】:2020-04-19 23:29:26
【问题描述】:

我在 Django 中创建了一个名为 text_field 的自定义模板标签

@register.inclusion_tag('form_field_tags/text_field.html')
def text_field(field, prefix=None, field_type=None, attr=None, **kwargs):
    return {
        'field': field,
        'prefix': prefix,
        'field_type': field_type,
        'placeholder': '',
        'attrs': parse_attrs(attr)
    }

parse_attrs 是一个函数,它接受像 class=form-control mb-4, v-model=property_name 这样的输入。

 {% text_field form.property_name attr="class=form-control mb-4, v-model=property_name" %}

parse_attrs 然后创建一个可以循环遍历的 HTML 属性和值的字典,因此在我的 text_field.html 中,我可以遍历从 text_field 自定义模板标签传入的所有 attrs

<label >
    {% if field.field.required %}
    <strong> {{ field.label }} <span> * </span> </strong>
    {% else %}
      {{ field.label }}
    {% endif %}
</label>
  <input
          {% if field_type == "password" %}
              type="password"
          {% else %}
              type="text"
          {% endif %}
          {% for attr, val in attrs.items %}
          {{ attr }} = {{ val }}
          {% endfor %}
          name="{% if prefix %}{{prefix}}-{% endif %}{{ field.name }}"
          placeholder="{{ placeholder }}"
          id="{% if prefix %}{{prefix}}-{% endif %}{{ field.name }}"
          {% if field.field.required %}
          required="required"
          {% endif %}
          {% if field.value %}
          value="{{ field.value }}"
          {% endif %}>

但是,当我尝试刷新浏览器并查看渲染输出时,我得到的是

<input type="text" class="form-control mb-4" name="property_name" placeholder="" id="property_name" required="required">

而不是这个

<input type="text" v-model="property_name" class="form-control mb-4" name="property_name" placeholder="" id="property_name" required="required">

有什么想法可以解决这个问题吗?

【问题讨论】:

    标签: html django vuejs2 django-templates vue-directives


    【解决方案1】:

    所以我意识到我使用的浏览器 (Firefox Dev) 在使用浏览器检查器查看时没有显示 v-model 指令,但是如果您查看通过网络选项卡在浏览器中发送的 HTML,则v-model 指令肯定存在,因此 Vue.js 会识别它。

    【讨论】:

      猜你喜欢
      • 2015-12-17
      • 2015-03-14
      • 2013-10-18
      • 2012-12-18
      • 2015-01-20
      • 2011-05-05
      • 2019-06-08
      • 1970-01-01
      • 2012-01-27
      相关资源
      最近更新 更多