将Django模型数组转换为alpine.js数组

r1wp621o  于 2023-03-04  发布在  Go
关注(0)|答案(1)|浏览(96)

我尝试将Django模型ArrayField转换为Alpine.js数组,如何解决这个问题?

x-on:click="offer_1 = !offer_1; currentJob={
                   title: '{{ job.title }}',
                    responsibilities: [{{ job.responsibilities }}] ???????,
                   }">

然后我想展示它:

<template x-for="responsibility in responsibilities">
              <li
                class="text-sm text-darkPurple font-light pl-5 bg-[url('../img/plus.svg')] bg-no-repeat bg-[top_4px_left] mb-4"
                x-text="responsibility">
              </li>
            </template>
uxhixvfz

uxhixvfz1#

Django有一个类似的过滤器json_script,但是它生成一个可以插入模板的<script id="data" type="application/json">{"hello": "world"}</script>字符串,我们可以修改它来生成一个内联转义JSON,它可以传递给Alpine.js变量。
在应用的templatetags文件夹中创建新的自定义过滤器(例如myapp_extras.py):

import json

from django import template
from django.core.serializers.json import DjangoJSONEncoder
from django.utils.safestring import mark_safe

register = template.Library()

_json_script_escapes = {
    ord(">"): "\\u003E",
    ord("<"): "\\u003C",
    ord("&"): "\\u0026",
}

@register.filter
def to_json(value):
    json_str = json.dumps(value, cls=DjangoJSONEncoder).translate(_json_script_escapes)

    return mark_safe(json_str)

在模板中,我们加载自定义过滤器并在数组上使用:

{% load myapp_extras %}

<a @click="currentJob={ responsibilities: {{ job.responsibilities|to_json }} }">

渲染后将变为如下所示:

<a @click="currentJob={ responsibilities: ['String #1', 'String #2'] }">

相关问题