3 ms·
<li>{{home}}</li> <li>{{home.features}}</li> <li>{{home.pricing}}</li> <li>{{home.contact}}</li> You saved one line of code, but had to pass related data
by metamemetics 16y ago
<li>{{home}}</li>
<li>{{home.features}}</li>
<li>{{home.pricing}}</li>
<li>{{home.contact}}</li>
You saved one line of code, but had to pass related data members that should be containerized in a home object to the template seperately, which means you actually used more total code if you include your view function. If you really want to do it that way, why not have a .list() interface method on your Home model that returns all of its string data members in a list?
{%for label in home.list%}
<li>{{label}}</li>
{%endfor%}
But I think the first way reads more like HTML and allows you to style them seperately which your going to have to often do 90% of the time
Edit: also, you can recurse all day long in django with clever use of the {%include%} tag. The {%include%} tag is seriously worth looking into in any complicated situation. Writing your HTML in seperate chunks also make rolling out an AJAX version of the page really easy, because you can just render the included subcomponent in an ajax request instead of the page that includes it, using the same view function.
- stevenwei 16y agoLike I said, it was a simplistic and contrived example. Obviously if the list was longer or the HTML contained more than a simple <li> tag, then the boilerplate repetition becomes more annoying. But who said anything about a Home model? What if I was just adding a list of links to the footer of my page? E.g. things that have nothing to do with the application or data but are necessary for presentation on a webpage.
- iamelgringo 16y agoYou're absolutely correct in saying that you shouldn't have to create boilerplate to have a footer with nav links on the bottom of every page. I believe that the preferred way to do this in Django is by either creating a custom template tag, or by using template inheritance. Template inheritance: create a base.html template with a {% block footer %} that can inherit and/or over ride it from any other template that needs. Template Tags: Create a simple tag that renders the comments thread, what's related links, etc... in a separate tag. This is the "preferred" way if you need to query the database for something that's related to multiple different views. For an example of that, see the django-pagination app.
- Daishiman 16y agoTemplate inheritance is the way to go, and it's one of the most important features necesary to create modular sites.