Django e-commerce part30 Django Template Include with Variable
Django Thumbnailを別のテンプレートに移す。
product_thumbnail.html を作成する。
product_list.htmlのthumbnailの機能のコードをproduct_thumbnail.htmlにコピペする。
<div class="thumbnail text-center"> <h4><a href='{{ product.get_absolute_url }}'>{{ product.title }}</a></h4> {% if product.get_image_url %} <a href='{{ product.get_absolute_url }}'><img id='img' class='img-responsive' src='{{ product.get_image_url }}' /></a></br> {% endif %} </div>
product_list.html に {% include "product_thumbnail.htmk"%} を追記する。
product_list.html
<div class='col-xs-4'> {% include "products/product_thumbnail.html " with product=product %} </div>
with includeファイルの変数名=こちらから渡す値
で代入可能。
product_detail.html も同様にproduct_thumbnail.html を使って修正する。
{% for product in related %} <div class='col-xs-6'> {% include "products/product_thumbnail.html" with product=product %} </div> {% cycle '' '</div><div class="row">'%} {% endfor %} </div>
product_thumbnail.html にもっと変数を入れてみる。
with price = "True" の場合、Priceを表示させるというコードを入れる。以下の例だと、商品のvariationの中から、1番上のものの、get_priceする。(get_priceは、sale_priceがある場合は、sale_price,それ以外の場合は、priceをゲットするfunction)
<div class="thumbnail text-center"> <h4><a href='{{ product.get_absolute_url }}'>{{ product.title }}</a></h4> {% if product.get_image_url %} <a href='{{ product.get_absolute_url }}'><img id='img' class='img-responsive' src='{{ product.get_image_url }}' /></a></br> {% endif %} {% if price == "True" %} {{ product.variation_set.first.get_price }} {% endif %} </div>
ちなみに、product_listのincludeは以下のような感じ。
{% include "products/product_thumbnail.html" with product=product price="True" %}
models.py のvariationに、get_html_price メソッドを追加する。
get_html_priceは、html用の装飾があらかじめ加えられたget_priceの変形版。
class Variation(models.Model): ... def get_html_price(self): if self.sale_price is not None: html_text = "<span class='sale-price'>%s</span> <span class='og-price'>%s</span>" %(self.sale_price, self.price) return html_text else: html_text = "<span class='price'>%s</span>" %(self.price) return html_text ...
product_thumbnail.html を修正
get_price→get_html_priceにコードを修正。ただ、これだけでは、コードがそのまま表示されてしまうので、|safe
を挿入する。
{% if price == "True" %} {{ product.variation_set.first.get_html_price|safe }} {% endif %}
safeは、エスケープしないように保護するという感じの意味らしいです。
Django テンプレート言語 — Django 1.4 documentation
products/models.py で、safeを組み込む
以下を参照にmark_safeを使ってみる。
Django Utils | Django documentation | Django
class Variation(models.Model): ... def get_html_price(self): if self.sale_price is not None: html_text = "<span class='sale-price'>%s</span> <span class='og-price'>%s</span>" %(self.sale_price, self.price) else: html_text = "<span class='price'>%s</span>" %(self.price) return mark_safe(html_text)