Include with Django

Published: Aug. 9, 2016, 5:02 p.m. Back

Author: rachell

I'm working on a current project that had a lot of repetative code. Then I discovered {% include filename.html %}

With this I was able to reduce repetative code which would elimate errors in there are any changes or updates. But also got 50 lines of code down to 6. 

I made a file, in this case, named program_base.html under the templates folder, with all the code that was repeated in different files. I then replaced the repetative code with {% include "program_base.html" %} and Voila! Magic! The updated file has 6 lines of code.  

{% extends "base.html" %}

{% block content %}
{% for program in artisanprograms %}

{% include "program_base.html" %}

{% endfor %}
{% endblock %}

 

I was really excited about this. I spent a lot of time making about 10 different pages and I learned a lot with that time but I'm so glad I found a way to not spend all the time writing similar code for different pages again. YAY! Use it if you can! 

New Comment