Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make Menu.get_template neutral to template engine #190

Merged
merged 5 commits into from
Nov 15, 2017
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion CONTRIBUTORS.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,12 @@
* Trent Holiday (trumpet2012)
* Tom Dyson (tomdyson)
* Oliver Bestwalter (obestwalter)
* Nguyễn Hồng Quân (hongquan)


## Translators

* François GUÉRIN (frague59)
* François GUÉRIN (frague59)
* Claudio Marinozzi (pyMan)
* Pierre Geier (bloodywing)
* Max Kurama (MaxKurama)
Expand Down
1 change: 1 addition & 0 deletions docs/source/rendering_menus/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@ Rendering menus

template_tag_reference
custom_templates
use_with_jinja2
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please remove this for now - We'll work on Jinja-specific stuff as a separate piece of work :)

96 changes: 96 additions & 0 deletions docs/source/rendering_menus/use_with_jinja2.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
.. _use_with_jinja2:

===============================
Use with Jinja2 template engine
===============================


If your project uses `Jinja2 <http://jinja.pocoo.org>`_ for template, the template for *wagtailmenus* has also be written in Jinja2. Assume that your source folder tree is like this::

+ project
| +-- settings.py
| +-- urls.py
+ templates
| +-- base.jinja
| +-- menus
+ manage.py


Here is how to make *wagtailmenus* work with Jinja2:

1. Create *jinja.py* file:

.. code-block:: python

import jinja2
from jinja2 import Environment
from jinja2.ext import Extension
from django.conf import settings
from wagtailmenus.templatetags.menu_tags import main_menu, sub_menu


def environment(**options):
env = Environment(**options)
env.globals.update({
'settings': settings,
})
return env


class MenuExtension(Extension):
def __init__(self, environment):
super().__init__(environment)
environment.globals.update({
'main_menu': jinja2.contextfunction(main_menu),
'sub_menu': jinja2.contextfunction(sub_menu),
})


2. Setup ``TEMPLATES`` in *settings.py* (not complete):

.. code-block:: python

from django_jinja.builtins import DEFAULT_EXTENSIONS

TEMPLATES = (
{
'NAME': 'django-jinja',
'BACKEND': 'django_jinja.backend.Jinja2',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'environment': 'project.jinja.environment',
'match_extension': '.jinja',
'extensions': DEFAULT_EXTENSIONS + [
'wagtail.wagtailcore.jinja2tags.core',
'wagtail.wagtailadmin.jinja2tags.userbar',
'wagtail.wagtailimages.jinja2tags.images',
# My extension for wagtailmenus
'project.jinja.MenuExtension',
],
}
},
)


Here in my example, I use `django-jinja <https://github.com/niwinz/django-jinja>`_ for integrating Jinja2 with Django. My convention is that template files are named with ".jinja" and put in *templates* folder.

3. Write your Jinja2 template for menu and change ``WAGTAILMENUS_DEFAULT_MAIN_MENU_TEMPLATE`` setting.

.. code-block:: python

WAGTAILMENUS_DEFAULT_MAIN_MENU_TEMPLATE = 'menus/main_menu.jinja'
WAGTAILMENUS_DEFAULT_SUB_MENU_TEMPLATE = 'menus/sub_menu.jinja'

You can copy original template of *wagtailmenus*, written in Django template syntax, and convert it to Jinja2.


4. In your template content, insert menu like this:

.. code-block:: jinja

<div class="collapse navbar-collapse" id="myNavbar">
{{ main_menu() }}
</div>


Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please remove this file for now - We'll work on Jinja-specific stuff as a separate piece of work :)

26 changes: 15 additions & 11 deletions wagtailmenus/models/menus.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

from django.db import models
from django.core.exceptions import ImproperlyConfigured, ValidationError
from django.template import Context
from django.template.loader import get_template, select_template
from django.utils import six
from django.utils.encoding import python_2_unicode_compatible
from django.utils.functional import cached_property, lazy
Expand Down Expand Up @@ -186,8 +186,8 @@ def render_to_template(self):
"""
context_data = self.get_context_data()
template = self.get_template()
context_data['current_template'] = template.name
return template.render(Context(context_data))
context_data['current_template'] = template.template.name
return template.render(context_data)

def clear_page_cache(self):
try:
Expand Down Expand Up @@ -303,7 +303,11 @@ def get_context_data(self, **kwargs):
the 'sub_menu' tag to render any additional levels."""
ctx_vals = self._contextual_vals
opt_vals = self._option_vals
data = ctx_vals.parent_context.flatten()
try:
data = ctx_vals.parent_context.flatten()
except AttributeError:
# Jinja2 Context
data = ctx_vals.parent_context.get_all()
data.update(ctx_vals._asdict())
data.update({
'apply_active_classes': opt_vals.apply_active_classes,
Expand Down Expand Up @@ -511,19 +515,19 @@ def modify_menu_items(self, menu_items):
"""
return menu_items

def get_template_engine(self):
return self._contextual_vals.parent_context.template.engine

def get_template(self):
engine = self.get_template_engine()
"""
In Django template backend case, returns the
``django.template.backends.django.Template`` instance.
"""
specified = self._option_vals.template_name
if specified:
return engine.get_template(specified)
return get_template(specified)
if self.template_name:
# Developers can set 'template_name' as a class attribute to have
# custom menus use specific templates
return engine.get_template(self.template_name)
return engine.select_template(self.get_template_names())
return get_template(self.template_name)
return select_template(self.get_template_names())

def get_template_names(self):
"""Return a list (or tuple) of template names to search for when
Expand Down
10 changes: 5 additions & 5 deletions wagtailmenus/models/mixins.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import absolute_import, unicode_literals

from django.utils.functional import cached_property
from django.template.loader import get_template, select_template

from .. import app_settings

Expand All @@ -9,13 +10,12 @@ class DefinesSubMenuTemplatesMixin(object):
sub_menu_template_name = None # set to use a specific default template

def get_sub_menu_template(self):
engine = self.get_template_engine()
specified = self._option_vals.sub_menu_template_name
if specified:
return engine.get_template(specified)
return get_template(specified)
if self.sub_menu_template_name:
return engine.get_template(self.sub_menu_template_name)
return engine.select_template(self.get_sub_menu_template_names())
return get_template(self.sub_menu_template_name)
return select_template(self.get_sub_menu_template_names())

@cached_property
def sub_menu_template(self):
Expand Down Expand Up @@ -52,7 +52,7 @@ def get_context_data(self, **kwargs):
"""
data = {}
if self._contextual_vals.current_level == 1 and self.max_levels > 1:
data['sub_menu_template'] = self.sub_menu_template.name
data['sub_menu_template'] = self.sub_menu_template.template.name
data.update(kwargs)
return super(DefinesSubMenuTemplatesMixin, self).get_context_data(
**data)