使用Django生成正確的HTML語義

[英]Producing the right HTML semantics with Django


I usually keep it simple and use the following form syntax in my templates:

我通常保持簡單,並在我的模板中使用以下表單語法:

<div>
       <div>{{form.title.label}}:</div>
       <div>{{form.title}}</div>
</div>

The problem with this approach is the bad semantic in the html output.

這種方法的問題是html輸出中的語義錯誤。

<div>
    <div>Title:</div>
    <div><input id="id_form-title" type="text" maxlength="30" name="form-title"></div>
</div>

Correct should be:

正確的應該是:

<div>
    <label for="id_form-title">Title</label>
    <input id="id_form-title" type="text" maxlength="30" name="form-title">
</div>

Is there a django build-in tag to do this automatically for me, or do I have to do it manually myself like this?

是否有django內置標簽為我自動執行此操作,或者我是否必須自己手動執行此操作?

<div>
    <label for="id_form-title">{{form.title.label}}</label>
    {{form.title}}
</div>

2 个解决方案

#1


3  

It is indeed annoying that outputting fields one by one doesn't give you automatic access to a properly-constructed label element - doing form.as_p will correctly produce the fields plus labels, but you give up all control over the form layout.

確實令人討厭的是,逐個輸出字段並不能讓您自動訪問正確構造的標簽元素 - 執行form.as_p將正確生成字段和標簽,但您放棄對表單布局的所有控制。

You can build up the label tag using the field information fairly easily though:

您可以非常輕松地使用字段信息構建標簽標記:

<label for="{{ field.auto_id }}">{{ field.label }}</label>
{{ field }}

You can put this in a template tag for easier reuse.

您可以將其放在模板標記中以便於重用。

Don't forget to also add {{ field.errors }} to display the errors associated with each field.

不要忘記添加{{field.errors}}以顯示與每個字段關聯的錯誤。

#2


2  

using label_tag should give you properly constructed label tag. So instead of just {{form.title.label}} you should use {{form.title.label_tag}} and it will result in the desired html

使用label_tag應該為您提供正確構造的標簽標簽。因此,您應該使用{{form.title.label_tag}},而不僅僅是{{form.title.label}},這將導致所需的html


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2012/11/20/7258179a144f7f5eb503648fc05795fd.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com