Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
836 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 Answer

0 votes
by (71.8m points)

Try this one,

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.6k users

...