Skip to content

Instantly share code, notes, and snippets.

@LowerDeez
Last active June 16, 2017 20:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LowerDeez/cfa382e2ae4aead0704dde49e18e313d to your computer and use it in GitHub Desktop.
Save LowerDeez/cfa382e2ae4aead0704dde49e18e313d to your computer and use it in GitHub Desktop.
Creating a model mixin to take care of meta tags
This mixin adds four filds to the model that extends from it: meta_keywords, meta_
description, meta_author, and meta_copyright. The methods to render the meta
tags in HTML are also added.
If you use this mixin in a model such as Idea, which is shown in the fist recipe of this
chapter, then you can put the following in the HEAD section of your detail page template
to render all the meta tags:
{{ idea.get_meta_tags }}
You can also render a specifi meta tag using the following line:
{{ idea.get_meta_description }}
As you may have noticed from the code snippet, the rendered meta tags are marked as safe,
that is, they are not escaped and we don't need to use the safe template fiter. Only the
values that come from the database are escaped in order to guarantee that the fial HTML
is well-formed.
# utils/models.py
# -*- coding: UTF-8 -*-
from __future__ import unicode_literals
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.template.defaultfilters import escape
from django.utils.safestring import mark_safe
class MetaTagsMixin(models.Model):
"""
Abstract base class for meta tags in the <head> section
"""
meta_keywords = models.CharField(
_("Keywords"),
max_length=255,
blank=True,
help_text=_("Separate keywords by comma."),
)
meta_description = models.CharField(
_("Description"),
max_length=255,
blank=True,
)
meta_author = models.CharField(
_("Author"),
max_length=255,
blank=True,
)
meta_copyright = models.CharField(
_("Copyright"),
max_length=255,
blank=True,
)
class Meta:
abstract = True
def get_meta_keywords(self):
tag = ""
if self.meta_keywords:
tag = '<meta name="keywords" content="%s" />\n' % escape(self.meta_keywords)
return mark_safe(tag)
def get_meta_description(self):
tag = ""
if self.meta_description:
tag = '<meta name="description" content="%s" />\n' % escape(self.meta_description)
return mark_safe(tag)
def get_meta_author(self):
tag = ""
if self.meta_author:
tag = '<meta name="author" content="%s" />\n' % escape(self.meta_author)
return mark_safe(tag)
def get_meta_copyright(self):
tag = ""
if self.meta_copyright:
tag = '<meta name="copyright" content="%s" />\n' % \
escape(self.meta_copyright)
return mark_safe(tag)
def get_meta_tags(self):
return mark_safe("".join((
self.get_meta_keywords(),
self.get_meta_description(),
self.get_meta_author(),
self.get_meta_copyright(),
)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment