如何在自定义 Django 模板标签中动态呈现 Vue.js 指令

How to dynamically render Vue.js directives in custom Django template tags

我在 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 中我可以循环所有传入的 attrs来自 text_field 自定义模板标签

<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">

关于如何解决这个问题有什么想法吗?

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