Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
961 views
in Technique[技术] by (71.8m points)

jinja2 - Django - How to take first word of a string in html template?

I have this list where I want to only get the first word (I would like to remove the "engineering" in all of them) and I am displaying this in my html template like this:

{% for course in courses %}
    <li>{{ course }}</li>
{% endfor %}

I also tried the following:

{% for course in courses %}
    <li>{{ course.split[0] }}</li>
{% endfor %}


{% for course in courses %}
    <li>{{ course[0] }}</li>
{% endfor %}

but those didn't work for me.

I tried to do this:

{% for course in courses %}
    <li>{{ course|first }}</li>
{% endfor %}

but it only gives me the first letter of each string. I know that i can do the truncate but not all of them have the same number of characters. I also tried to do this but to no avail. Maybe some my syntax above were wrong. What solutions can I try? Thanks in advance!

question from:https://stackoverflow.com/questions/65857520/django-how-to-take-first-word-of-a-string-in-html-template

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this one,

{% for course in courses %}
{% set words = course.split(' ') %}
<li>{{ words[0] }}</li>
{% endfor %}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...