views:

87

answers:

2

As an example, let's say there's a Tshirt model on a shopping site, and it will have "summary" markup with a thumbnail, name and price:

<div>
    <a href="detailspage">Awesome TShirt!</a>
    <img src="thumbnail.jpg" />
    <span class="price">$55.99</span>
</div>

Since this will be on many different pages, I don't want to have to type this out over and over in different templates. What I would prefer is a call in the template to a method like tshirt.show_summary() that would return this html.

But if we put it in the model, we're mixing our presentation and model layers.

Is there any workaround for this, or do we just suck it up and violate either MTV or DRY?

+2  A: 

Consider making it an inclusion tag: http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#inclusion-tags

{% show_summary tshirt %}

dar
+2  A: 

Put your HTML code in a template and use {% include %} to load it. Here's an example:

item.html

<div>
    <a href="{% url tshirt_details item">{{ item.name }}</a>
    <img src="{{ item.image.url }}" />
    <span class="price">${{ item.price }}</span>
</div>

tshirt_list.html

{% for tshirt in object_list %}
    {% with tshirt as item %}
        {% include "item.html" %}
    {% endwith %}
{% endfor %}

Inclusion tags, like dar suggests, are also often used for such scenarios.

piquadrat