nephila / django-meta

Pluggable app to allow Django developers to quickly add meta tags and OpenGraph, Twitter, and Google Plus properties to their HTML responses.
https://django-meta.readthedocs.io
Other
480 stars 68 forks source link

Adding meta tags to Flatpages #142

Closed philgyford closed 1 year ago

philgyford commented 1 year ago

I'm using the Flatpages app and would like to use django-meta's meta tags when rendering a custom template for a Flatpage. But I can't work out if there's a way to hook them together. Some options I've considered:

So I wonder if I'm either missing some sensible way of doing this, or if it's not possible.

(Hope this is an acceptable use of an Issue; please do close it if not, sorry.)

yakky commented 1 year ago

@philgyford You can create a templatetag that gets the flat page is input and store the meta objects in the context (eg: {% flatpage_meta flatpage as meta %}) which internally instantiates Meta and returns the instance

philgyford commented 1 year ago

@yakky Thank you for that pointer! I've got something working, and for anyone else who comes across this...

I already have a view mixin that does a load of custom stuff for my site:

from meta.views import MetadataMixin

class MyMetadataMixin(MetadataMixin):
    # My custom methods

So I created a tiny view solely to be able to use that same mixin to generate the required data in the same way for flatpages as every other page with its own view:

from django.views import View
from django.views.generic.base import ContextMixin

class FlatpageMetaView(MyMetadataMixin, ContextMixin, View):
    pass

Then I created a template tag in myapp/templatetags/flatpages.py that instantiates that view, passes in the Flatpage's title, and generates the context data:

from django import template
from ..views import FlatpageMetaView

register = template.Library()

@register.simple_tag
def get_flatpage_meta(flatpage, request):
   "Returns a django-meta Meta object for the supplied Flatpage, to generate meta tags."
    view = FlatpageMetaView(title=flatpage.title, request=request)
    context_data = view.get_context_data()
    return context_data["meta"]

Finally, my base.html template used to start something like this:

<!DOCTYPE html>
{% load meta static %}
<html lang="en">
<head {% meta_namespaces %}>
  <meta charset="UTF-8">
  {% include 'meta/meta.html' %}

I changed it to load the flatpages template tag and generate the meta context data if there's a flatpage present:

<!DOCTYPE html>
{% load flatpages meta static %}

{% if flatpage %}
  {% get_flatpage_meta flatpage request as meta %}
{% endif %}

<html lang="en">
<head {% meta_namespaces %}>
  <meta charset="UTF-8">
  {% include 'meta/meta.html' %}
yakky commented 1 year ago

awesome :)