简体   繁体   中英

django templates string formatting

I want to pad and cut too long chars. So I used stringformat. In this example, I want my string to be 10 characters long, with padding if necessary. I have this code in my django template

{{ "my too long or too short string"|stringformat:":10" }}

But django outputs nothing.

使用内部truncatechars模板标签

{{ "my too long or too short string"|truncatechars:10 }}

Django 1.10 , docs here ,

Use truncatechars , rjust together.

index.html

<p>Non formated string</p>
<p>{{ "Truncatechars (include ... length)"|truncatechars:10}}</p>
<p>{{ "Truncatechars with rjust"|truncatechars:10|rjust:"30" }}</p>
<p>{{ "Only rjust"|rjust:"30" }}</p>

Output

Template renders correct HTML as below.

Please note white-space: pre; css property to represent white-space.

 p { white-space: pre; } 
 <p>Non formated string</p> <p>Truncat...</p> <p> Truncat...</p> <p> Only rjust</p> 

About white-space, see here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM