On Jun 25, 6:52 pm, "Daniele Procida" <[email protected]>
wrote:
> I created a simple_tag:
>
> def news_for_this_page(page):
> if page.entity_set.all(): # check page belongs to an entity first
> e = page.entity_set.all()[0] # first entity will be only one
> newslist = []
> for item in e.newsitem_set.all(): # get entity's news items
> newslist.append(item.headline) # add them to the list
> return newslist
> else:
> return "No news is good news"
>
> What this spits back into the page is:
>
> [u'Man bites dog', u'Dog bites man', u'Nixon resigns']
>
> so obviously I need to process that list, making it a <ul> and putting
> in the links before sending that to the template.
>
> To do this, I think I need my function to call another template to
> render it appropriately - is that correct?
>
> Are there any shortcuts in this process?
>
> For example, to use my template tag I use {% news_for_this_page entity
> %}. It would be neater to use something like {% news_for_this_page %},
> since entity will always be set.
>
> Thanks,
>
> Daniele
The best thing to do here is to use an 'inclusion tag', which as the
documentation says is a template tag that renders another template. So
you'd define a small template with just the html for rendering your
news list, then pass that as the argument to the decorator when
defining the tag. The function then returns a dictionary context, as
you would use in a view.
The second thing you can do with the inclusion tag - to answer your
other question - is to use the decorator with takes_context=True. Then
it will take a single parameter, context, which is the parent
template's context, so you don't need to pass in your object
explicitly.
@register.inclusion_tag('newslist.html', takes_context=True)
def news_for_this_page(context):
...
return {'newslist': newslist}
See the documentation:
http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#inclusion-tags
--
DR.
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Django users" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---