Search code examples
djangojinja2

Django: How to get the first word of a string in an HTML template?


Problem

I am passing a list to my HTML template and the list looks like this:

Chemical Engineering
Civil Engineering
Computer Engineering
Electrical Engineering
Electronics Engineering
...

My Goal

I want to grab the first word (I would like to remove the "engineering" in all of them). I'm displaying the list in my HTML template like this:

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

What I tried

I tried the following syntax:

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

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

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

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


Solution

  • Based on schwobaseggl's comment, he mentioned trying the syntax course.split.0 and it worked for me.