1

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!

sudocat
  • 129
  • 1
  • 3
  • 11
  • your `course` is a string type, and the `first` would give you the first letter. that's expected. You need to somehow make course a list consist of 2 words first. You can either do it in the backend or create a custom filter for that. Essentially it does `your_string.split(' ')` – JChao Jan 23 '21 at 09:22
  • 2
    In the template you should be able to do: `course.split.0` to get the first token. At least in the django templating engine. With jinja2, I am not sure, but it is even less restricting. – user2390182 Jan 23 '21 at 09:25
  • Thanks schwobaseggl! This was exactly what I was looking for. – sudocat Jan 25 '21 at 02:37

2 Answers2

6

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

sudocat
  • 129
  • 1
  • 3
  • 11
1

Try this one,

{% for course in courses %}
{% set words = course.split(' ') %}
<li>{{ words[0] }}</li>
{% endfor %}
Abrar Malekji
  • 111
  • 1
  • 4