Django choices to js `' `(html select option)

2022-08-23 15:28:44 浏览数 (1)

要件:

typeChoices→html:select > option

key-value:【<option value="`{{value}}`">{{name}}</option>】

代码语言:python代码运行次数:0复制
from django.db import models
class typeChoices(models.TextChoices):
    NEW = '新規', '新規'
    UPD= '修正', '修正'

问题&注意:

问题:单引号会以hex形式出现【 &#x27;】

解决:

let choices ={{type_choices|safe}}

対策:

1, convert to array

代码语言:python代码运行次数:0复制
pj>util>convert.py
from django.db import models
    
def get_js_choices(choice:models.TextChoices):
    """js filter choices

    Args:
        choice (models.TextChoices): choices

    Returns:
        array: js choices
    """
    js_choices = []
    for c in choice:
        ch = {}
        ch["name"] = c.value
        ch["value"] = c.value
        js_choices.append(ch)
    return js_choices

2, init process

代码语言:javascript复制
pj>xx>list_view.py

def list_init(request):
    """初期化"""
    context = {}
    context['type_choices'] = get_js_choices(typeChoices)  # js 使用
    context['type_choices'] = typeChoices.choices          # django templete 使用

    return render(request, 'master/xx_list.html',context)

3, templete :

① js 使用 (handsbar)

safe :若不加,单引号会以hex形式出现【' 】

代码语言:javascript复制
let choices = {{type_choices|safe}}              # safe :若不加,单引号会以hex形式出现【&#x27; 】
 
var str = `
<div class="select ml-2 is-small"  >
    <select class="field-value" style="width:30rem;">
        {{#each choices}}
        <option value="{{value}}">{{name}}</option>
        {{/each}}
    </select>
</div>
`;

var value_template = Handlebars.compile(str); 

② django templete 使用

代码语言:javascript复制
<select id="type" name="type">
	<option></option>
	{% for op in type_choices %}
		<option value="{{op}}">{{op}}</option>
	{% endfor %}
</select>

0 人点赞