user123892
user123892

Reputation: 1325

How to pass an argument from SnippetChooserPanel to a django-template

in my-django-project, I've successfully implemented a wagtail-driven app that allows to reference the model Map() of my-django-projectas a snippet in wagtail/admin(as described here).

My problem now is that when I choose (in the SnippetChooserPanel) the instance of Map() to be integrated in my wagtail template, my choice gets lost and my template renders all the instances found in Map() table. This is because my choice in SnippetChooserPanel is not passed to the wagtail-app template.

my wagtail-app/models.py

class HomePage(Page):
    [..]    
    maps = models.ForeignKey(
        'maps.Map',
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name='+'
    )

    [..]
    class Meta:
        verbose_name = "Homepage"

HomePage.content_panels = Page.content_panels + [
        [..]
        SnippetChooserPanel('maps')
        ]

my-django-project.maps.templates.maps/maps.html

{% load wagtailimages_tags wagtailadmin_tags %}
{% load i18n %}

{% for map in maps %}
    <div class="col-xs-4 item-thumb">
        <a href="{{ map.detail_url }}"><img src="{{ map.thumbnail_url }}" />
        </a>
    </div>
{% endfor %}

my-django-project.maps.templatetags/maps_tags.html

from django import template
from geonode.maps.models import Map

register = template.Library()

# Map snippets
@register.inclusion_tag('maps/maps.html', takes_context=True)
def maps(context):
    print("QUI \n")
    return {
        'maps': Map.objects.all(),
        'request': context['request'],
    }

my wagtail-app.templates/home_page.html

{% load maps_tags %}

<div class="mine">
[...]
{% maps %}
</div>

I'm new to Wagtail and there is not much documentation on SnippetChooserPanel handling..

Do you have any hints?

Thank you in advance for any help you could provide.

Upvotes: 0

Views: 567

Answers (1)

gasman
gasman

Reputation: 25292

Your chosen Map instance is stored on the page object as the field maps, so you can refer to page.maps in your template code, just as you would refer to (for example) page.title. (Since it only links to one map, it would probably make sense to rename the field to map.)

There's no real reason to use a template tag here - you could just insert the relevant HTML directly into your home_page.html template:

<div class="col-xs-4 item-thumb">
    <a href="{{ page.maps.detail_url }}"><img src="{{ page.maps.thumbnail_url }}" />
    </a>
</div>

or move that HTML snippet into its own template, included using the {% include %} tag:

templates/maps/map.html:

<div class="col-xs-4 item-thumb">
    <a href="{{ map.detail_url }}"><img src="{{ map.thumbnail_url }}" />
    </a>
</div>

home_page.html:

{% include "maps/map.html" with map=page.maps %}

Upvotes: 2

Related Questions