本文整理汇总了Python中coffin.template.Library类的典型用法代码示例。如果您正苦于以下问题:Python Library类的具体用法?Python Library怎么用?Python Library使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Library类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _load_lib
def _load_lib(lib):
if not isinstance(lib, CoffinLibrary):
# If this is only a standard Django library,
# convert it. This will ensure that Django
# filters in that library are converted and
# made available in Jinja.
lib = CoffinLibrary.from_django(lib)
extensions.extend(getattr(lib, 'jinja2_extensions', []))
filters.update(getattr(lib, 'jinja2_filters', {}))
globals.update(getattr(lib, 'jinja2_globals', {}))
tests.update(getattr(lib, 'jinja2_tests', {}))
attrs.update(getattr(lib, 'jinja2_environment_attrs', {}))
示例2: _get_templatelibs
def _get_templatelibs(self):
"""Return an iterable of template ``Library`` instances.
Since we cannot support the {% load %} tag in Jinja, we have to
register all libraries globally.
"""
from django.conf import settings
from django.template import get_library, InvalidTemplateLibrary
libs = []
for a in settings.INSTALLED_APPS:
try:
path = __import__(a + '.templatetags', {}, {}, ['__file__']).__file__
path = os.path.dirname(path) # we now have the templatetags/ directory
except ImportError:
pass
else:
for f in os.listdir(path):
if f == '__init__.py':
continue
if f.endswith('.py'):
try:
# TODO: will need updating when #6587 lands
# libs.append(get_library(
# "django.templatetags.%s" % os.path.splitext(f)[0]))
l = get_library(os.path.splitext(f)[0])
if not isinstance(l, CoffinLibrary):
# If this is only a standard Django library,
# convert it. This will ensure that Django
# filters in that library are converted and
# made available in Jinja.
l = CoffinLibrary.from_django(l)
libs.append(l)
except InvalidTemplateLibrary:
pass
return libs
示例3: Library
from coffin.template import Library
from django.contrib.staticfiles.storage import staticfiles_storage
from coffin.templatetags.static import StaticExtension as CoffinStaticExtension
register = Library()
class StaticExtension(CoffinStaticExtension):
"""Implements the {% static %} tag as provided by the ``staticfiles``
contrib module.
Returns the URL to a file using staticfiles' storage backend.
Usage::
{% static path [as varname] %}
Examples::
{% static "myapp/css/base.css" %}
{% static variable_with_path %}
{% static "myapp/css/base.css" as admin_base_css %}
{% static variable_with_path as varname %}
"""
@classmethod
def get_static_url(cls, path):
return super(StaticExtension, cls).get_static_url(
staticfiles_storage.url(path))
示例4: set
tags = set(['csrf_token'])
def parse(self, parser):
lineno = parser.stream.next().lineno
return nodes.Output([
self.call_method('_render', [nodes.Name('csrf_token', 'load')]),
]).set_lineno(lineno)
def _render(self, csrf_token):
from django.template.defaulttags import CsrfTokenNode
return Markup(CsrfTokenNode().render({'csrf_token': csrf_token}))
# nicer import names
load = LoadExtension
url = URLExtension
with_ = WithExtension
cache = CacheExtension
spaceless = SpacelessExtension
csrf_token = CsrfTokenExtension
register = Library()
register.tag(load)
register.tag(url)
register.tag(with_)
register.tag(cache)
register.tag(spaceless)
register.tag(csrf_token)
示例5: parse
"""
tags = ['spaceless']
def parse(self, parser):
lineno = parser.stream.next().lineno
body = parser.parse_statements(['name:endspaceless'], drop_needle=True)
return nodes.CallBlock(
self.call_method('_strip_spaces', [], [], None, None),
[], [], body
).set_lineno(lineno)
def _strip_spaces(self, caller=None):
from django.utils.html import strip_spaces_between_tags
return strip_spaces_between_tags(caller().strip())
# nicer import names
load = LoadExtension
url = URLExtension
with_ = WithExtension
cache = CacheExtension
spaceless = SpacelessExtension
register = Library()
register.tag(load)
register.tag(url)
register.tag(with_)
register.tag(cache)
register.tag(spaceless)
示例6: Library
try:
from urllib.parse import urljoin
except ImportError: # Python 2
from urlparse import urljoin
from coffin.template import Library
from jinja2.ext import Extension
from jinja2 import nodes
from django.utils.encoding import iri_to_uri
register = Library()
class PrefixExtension(Extension):
def parse(self, parser):
stream = parser.stream
lineno = stream.next().lineno
call_node = self.call_method('render')
if stream.next_if('name:as'):
var = nodes.Name(stream.expect('name').value, 'store')
return nodes.Assign(var, call_node).set_lineno(lineno)
else:
return nodes.Output([call_node]).set_lineno(lineno)
def render(self, name):
raise NotImplementedError()
示例7: Library
import urllib
import hashlib
from django.conf import settings
from django.contrib.sites.models import Site
from django.utils.translation import get_language_from_request, ugettext
if 'coffin' in settings.INSTALLED_APPS:
from coffin.template import Library
from jinja2 import Markup as mark_safe
else:
from django.template import Library
from django.utils.safestring import mark_safe
register = Library()
if 'coffin' in settings.INSTALLED_APPS:
register.simple_tag = register.object
def current_site_url():
"""Returns fully qualified URL (no trailing slash) for the current site."""
protocol = getattr(settings, 'MY_SITE_PROTOCOL', 'https')
port = getattr(settings, 'MY_SITE_PORT', '')
url = '%s://%s' % (protocol, settings.SITE_DOMAIN)
if port:
url += ':%s' % port
return url
@register.simple_tag
示例8: AssetsNode
filters = value
warnings.warn('The "filter" option of the {% assets %} '
'template tag has been renamed to '
'"filters" for consistency reasons.',
ImminentDeprecationWarning)
# positional arguments are source files
elif name is None:
files.append(value)
else:
raise template.TemplateSyntaxError('Unsupported keyword argument "%s"'%name)
# capture until closing tag
childnodes = parser.parse(("endassets",))
parser.delete_first_token()
return AssetsNode(filters, output, files, childnodes)
# If Coffin is installed, expose the Jinja2 extension
try:
from coffin.template import Library as CoffinLibrary
except ImportError:
register = template.Library()
else:
register = CoffinLibrary()
from webassets.ext.jinja2 import AssetsExtension
from django_assets.env import get_env
register.tag(AssetsExtension, environment={'assets_environment': get_env()})
# expose the default Django tag
register.tag('assets', assets)
示例9: Library
# coding=utf8
from urlparse import urljoin
from coffin.template import Library
from jinja2.ext import Extension
from jinja2 import nodes
from django.utils.encoding import iri_to_uri
from django.conf import settings
from models import StaticFile
register = Library()
class PrefixExtension(Extension):
def parse(self, parser):
stream = parser.stream
lineno = stream.next().lineno
call_node = self.call_method('render')
if stream.next_if('name:as'):
var = nodes.Name(stream.expect('name').value, 'store')
return nodes.Assign(var, call_node).set_lineno(lineno)
else:
return nodes.Output([call_node]).set_lineno(lineno)
def render(self, name):
raise NotImplementedError()
@classmethod
示例10: Library
from coffin.template import Library
from django.template.loader import render_to_string
from jinja2 import nodes
from jinja2.ext import Extension
register = Library()
class MerchantExtension(Extension):
tags = set(['render_integration'])
def parse(self, parser):
stream = parser.stream
lineno = stream.next().lineno
obj = parser.parse_expression()
call_node = self.call_method('render_integration', args=[obj])
return nodes.Output([call_node]).set_lineno(lineno)
@classmethod
def render_integration(self, obj):
form_str = render_to_string(obj.template, {'integration': obj})
return form_str
register.tag(MerchantExtension)
示例11: foo
"""Register a portable filter with a Coffin library object.
"""
def foo(value):
return "{foo}"
from coffin.template import Library
register = Library()
register.filter('foo', foo)
示例12: Library
from django.conf import settings
if 'coffin' in settings.INSTALLED_APPS:
from jinja2 import nodes, Markup
from jinja2.ext import Extension
from coffin.template import Library
from guide.templatetags.guide_tags import AddGuide, render_guides as origin_render_guides
register = Library()
class AddGuideExtension(Extension):
"""
Jinja2-version of the ``render_guides`` tag.
"""
tags = set(['add_guide'])
def parse(self, parser):
lineno = parser.stream.next().lineno
args = []
while not parser.stream.current.test('block_end'):
args.append(parser.parse_expression())
parser.stream.skip_if('comma')
return nodes.Output([
self.call_method('_render', [nodes.Name('request', 'load'), nodes.List(args)]),
]).set_lineno(lineno)
def _render(self, request, args):
if not hasattr(request, 'current_guide_name_list'):
request.current_guide_name_list = list()
示例13: environment
from jinja2 import environmentfilter, contextfilter
@environmentfilter
def environment(environment, value):
return ""
@contextfilter
def context(context, value):
return ""
def multiarg(value, arg1, arg2):
return ""
def jinja_forced(value):
return ""
def django_jinja_forced(value):
# a django filter that returns a django-safestring. It will *only*
# be added to jinja, and coffin will hopefully ensure the string
# stays safe.
from django.utils.safestring import mark_safe
return mark_safe(value)
from coffin.template import Library
register = Library()
register.filter('environment', environment)
register.filter('context', context)
register.filter('multiarg', multiarg)
register.filter('jinja_forced', jinja_forced, jinja2_only=True)
register.filter('django_jinja_forced', django_jinja_forced, jinja2_only=True)
示例14: FooExtension
"""Register a Jinja2 extension with a Coffin library object.
"""
from jinja2.ext import Extension
from jinja2 import nodes
class FooExtension(Extension):
tags = set(['foo'])
def parse(self, parser):
parser.stream.next()
return nodes.Const('{foo}')
from coffin.template import Library
register = Library()
register.tag(FooExtension)
示例15: pdb_with_context
if self.use_pdb:
pdb_with_context(context)
else:
setup_readline_history()
run_shell(context)
return ''
@register.tag
def repl(parser, token):
use_pdb = False
bits = token.contents.split()
if len(bits) > 1:
if bits[1] == 'pdb':
use_pdb = True
else:
raise TemplateSyntaxError('The second argument to the "repl" tag, if present, must be "pdb".')
return REPLNode(use_pdb)
try:
from coffin.template import Library as CoffinLibrary
import coffin.common
except ImportError:
pass
else:
# We could simply create a Coffin library in the first place,
# of course, but this allows us to more easily maintain this
# change as a fork.
from template_repl.jinja2_ext import REPLExtension
register = CoffinLibrary.from_django(register)
register.tag(REPLExtension)