View All Posts. MiCHiLU.com powered by Django ;-)

[Django]: Inclusion Tag に Custom Context を詰め込む

Template だからといって勝手に Context が入るというわけではないみたい。 受け取った context に update して返すのがスマートそう。

Python プログラマのための Django テンプレート言語ガイド - 埋め込みタグ (inclusion tag):
http://michilu.com/django/doc-ja/templates_python/#id26

実際のコードを編集しているので、動かないかもしんない。 あまりピンと来ない例になってしまったけど、便利な時が来るかもしれないので張っておこう。

myproject/app/context_processors.py

from django.conf import settings

def context(request):
    return {
        "MEDIA_URL": settings.MEDIA_URL,
    }

myproject/app/templatetags/extras.py

from django.template import Library
from myproject.app.models import Entry

register = Library()

@register.inclusion_tag("tags/entry.html", takes_context=True)
def entry_list(context, tag, num):
    context.update({"entries": Entry.objects.filter(tags=tag)[:int(num)]})
    return context

myproject/app/templates/tags/entry.html

{% for entry in entries %}<li>
<a href="{{ entry.get_absolute_url }}">{{ entry.title|escape }}</a>
<img src="{{ MEDIA_URL }}img/{{ entry.tags }}.png" />
</li>
{% endfor %}

myproject/app/tests.py

>>> import context_processors
>>> context = context_processors.context(request=None)
>>> context.keys()
['MEDIA_URL']

>>> from templatetags import extras
>>> entries = extras.entry_list(context, "test", "3")
>>> entries.keys()
['MEDIA_URL', 'entries']
>>> for entry in entries["entries"]:
...     entry.id, entry.title
(6, 'test_title')
(5, 'test_title')
(4, 'test_title')

>>> context["MEDIA_URL"] = "##MEDIA_URL##"  #for TEST

>>> from django.template import Context, Template
>>> t = Template('{% load extras %}{% entry_list "id" "3" %}')
>>> print t.render(Context(context))
<li>
<a href="/entry/6/">test_title</a>
<img src="##MEDIA_URL##img/test.png" />
</li>
<li>
<a href="/entry/5/">test_title</a>
<img src="##MEDIA_URL##img/test.png" />
</li>
<li>
<a href="/entry/4/">test_title</a>
<img src="##MEDIA_URL##img/test.png" />
</li>
<BLANKLINE>
Tue, 8 May 2007 01:13:29 +0900 source edit
Creative Commons License
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 2.1 Japan License.
View All Posts. MiCHiLU.com powered by Django ;-)