Last active
August 29, 2015 14:19
-
-
Save sthzg/2883cfda500bd807e0ee to your computer and use it in GitHub Desktop.
Resolving views from other views and template tags
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# e.g. in myapp/templatetags/myapp_extras.py | |
from __future__ import absolute_import, unicode_literals | |
from django import template | |
from patterntests.views import SomePartial | |
register = template.Library() | |
def somepartial(context): | |
someview = SomePartial() | |
res = someview.get(context.get('request')) | |
return res.content | |
register.simple_tag(takes_context=True)(somepartial) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.core.urlresolvers import reverse, resolve | |
from django.shortcuts import render | |
from django.utils.safestring import mark_safe | |
from django.views.generic.base import View | |
class SomePartial(View): # /myapp/partials/somepartial/ | |
""" A view providing partial content. | |
""" | |
def get(self, request): | |
return render(request, 'patterntests/_partial.html', {}) | |
class SomeView(View): # /myapp/someview/ | |
""" Including the partial content by calling get on `SomePartial`. | |
""" | |
def get(self, request): | |
someview = SomePartial() | |
res = someview.get(request) | |
ctx = { | |
'partial_content': mark_safe(res.content) | |
} | |
return render(request, 'patterntests/test.html', ctx) | |
class AnotherView(View): # /myapp/anotherview/ | |
""" Including the partial by resolving its through its url. | |
""" | |
def get(self, request): | |
rev = reverse('patterntests:somepartial') | |
view, vargs, vkwargs = resolve(rev) | |
vkwargs['request'] = request | |
res = view(*vargs, **vkwargs) | |
ctx = { | |
'partial_content': mark_safe(res.content) | |
} | |
return render(request, 'patterntests/test.html', ctx) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment