当前位置: 首页>>代码示例>>Python>>正文


Python template.Library类代码示例

本文整理汇总了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', {}))
开发者ID:desres,项目名称:coffin,代码行数:12,代码来源:common.py

示例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
开发者ID:HubertD,项目名称:coffin,代码行数:37,代码来源:common.py

示例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))
开发者ID:spothero,项目名称:coffin,代码行数:31,代码来源:static.py

示例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)

开发者ID:Eksmo,项目名称:coffin,代码行数:28,代码来源:defaulttags.py

示例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)
开发者ID:ALBAstryde,项目名称:albastryde,代码行数:31,代码来源:defaulttags.py

示例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()
开发者ID:spothero,项目名称:coffin,代码行数:30,代码来源:static.py

示例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
开发者ID:ilblackdragon,项目名称:django-misc,代码行数:30,代码来源:share_buttons.py

示例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)
开发者ID:chexov,项目名称:webassets,代码行数:31,代码来源:assets.py

示例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
开发者ID:torpedoallen,项目名称:django-cdn-extension,代码行数:31,代码来源:extensions.py

示例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)
开发者ID:BrajeshKhare,项目名称:merchant,代码行数:28,代码来源:jinja2_tags.py

示例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)
开发者ID:Deepwalker,项目名称:coffin,代码行数:9,代码来源:portable_filters.py

示例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()
开发者ID:frol,项目名称:django-guide,代码行数:31,代码来源:jinja2_guide_tags.py

示例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)
开发者ID:Deepwalker,项目名称:coffin,代码行数:31,代码来源:jinja2_filters.py

示例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)
开发者ID:HubertD,项目名称:coffin,代码行数:16,代码来源:foo_ext.py

示例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)
开发者ID:miracle2k,项目名称:django-template-repl,代码行数:31,代码来源:repl.py


注:本文中的coffin.template.Library类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。