Sometimes, we want to split string to array with Python Django templates.
In this article, we’ll look at how to split string to array with Python Django templates.
How to split string to array with Python Django templates?
To split string to array with Python Django templates, we can create our own model method to do the splitting.
For instance, we write
class Game(models.Model):
#...
def screenshots_as_list(self):
return self.screenshots.split('\n')
to create the Game
model with the screenshots_as_list
method to return the screenshots
string field split into an array by the newline.
And then in our template, we use it by writing
{% for screen in game.screenshots_as_list %}
{{ screen }}<br>
{% endfor %}
Conclusion
To split string to array with Python Django templates, we can create our own model method to do the splitting.