本文整理汇总了Python中django.template.base.Library类的典型用法代码示例。如果您正苦于以下问题:Python Library类的具体用法?Python Library怎么用?Python Library使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Library类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: load
def load(parser, token):
"""
Loads a custom template tag set.
For example, to load the template tags in
``django/templatetags/news/photos.py``::
{% load news.photos %}
Can also be used to load an individual tag/filter from
a library::
{% load byline from news %}
"""
bits = token.contents.split()
if len(bits) >= 4 and bits[-2] == "from":
try:
taglib = bits[-1]
lib = get_library(taglib)
except InvalidTemplateLibrary, e:
raise TemplateSyntaxError("'%s' is not a valid tag library: %s" % (taglib, e))
else:
temp_lib = Library()
for name in bits[1:-2]:
if name in lib.tags:
temp_lib.tags[name] = lib.tags[name]
# a name could be a tag *and* a filter, so check for both
if name in lib.filters:
temp_lib.filters[name] = lib.filters[name]
elif name in lib.filters:
temp_lib.filters[name] = lib.filters[name]
else:
raise TemplateSyntaxError("'%s' is not a valid tag or filter in tag library '%s'" % (name, taglib))
parser.add_library(temp_lib)
示例2: load
def load(parser, token):
"""
Loads a custom template tag set.
For example, to load the template tags in
``django/templatetags/news/photos.py``::
{% load news.photos %}
Can also be used to load an individual tag/filter from
a library::
{% load byline from news %}
"""
# token.split_contents() isn't useful here because this tag doesn't accept variable as arguments
bits = token.contents.split()
if len(bits) >= 4 and bits[-2] == "from":
try:
taglib = bits[-1]
lib = get_library(taglib)
except InvalidTemplateLibrary as e:
raise TemplateSyntaxError("'%s' is not a valid tag library: %s" %
(taglib, e))
else:
temp_lib = Library()
for name in bits[1:-2]:
if name in lib.tags:
temp_lib.tags[name] = lib.tags[name]
# a name could be a tag *and* a filter, so check for both
if name in lib.filters:
temp_lib.filters[name] = lib.filters[name]
elif name in lib.filters:
temp_lib.filters[name] = lib.filters[name]
else:
raise TemplateSyntaxError("'%s' is not a valid tag or filter in tag library '%s'" %
(name, taglib))
parser.add_library(temp_lib)
else:
for taglib in bits[1:]:
# add the library to the parser
try:
lib = get_library(taglib)
parser.add_library(lib)
except InvalidTemplateLibrary as e:
raise TemplateSyntaxError("'%s' is not a valid tag library: %s" %
(taglib, e))
return LoadNode()
示例3: Library
"""Default tags used by the template system, available to all templates."""
import sys
import re
from itertools import groupby, cycle as itertools_cycle
from django.template.base import Node, NodeList, Template, Context, Variable
from django.template.base import TemplateSyntaxError, VariableDoesNotExist, BLOCK_TAG_START, BLOCK_TAG_END, VARIABLE_TAG_START, VARIABLE_TAG_END, SINGLE_BRACE_START, SINGLE_BRACE_END, COMMENT_TAG_START, COMMENT_TAG_END
from django.template.base import get_library, Library, InvalidTemplateLibrary
from django.template.smartif import IfParser, Literal
from django.conf import settings
from django.utils.encoding import smart_str, smart_unicode
from django.utils.safestring import mark_safe
register = Library()
# Regex for token keyword arguments
kwarg_re = re.compile(r"(?:(\w+)=)?(.+)")
def token_kwargs(bits, parser, support_legacy=False):
"""
A utility method for parsing token keyword arguments.
:param bits: A list containing remainder of the token (split by spaces)
that is to be checked for arguments. Valid arguments will be removed
from this list.
:param support_legacy: If set to true ``True``, the legacy format
``1 as foo`` will be accepted. Otherwise, only the standard ``foo=1``
format is allowed.
:returns: A dictionary of the arguments retrieved from the ``bits`` token
示例4: import
# -*- coding: utf-8 -*-
from classytags.arguments import Flag, StringArgument
from classytags.core import Options
from django.template.base import Library
from classytags.helpers import InclusionTag
from adminlinks.templatetags.utils import (context_passes_test, get_admin_site,
get_registered_modeladmins,
_resort_modeladmins)
register = Library()
class AdminlinksToolbar(InclusionTag):
template = 'adminlinks/toolbar.html'
options = Options(
Flag('with_labels',
true_values=['1', 'true', 'yes', 'on'],
false_values=['0', 'false', 'no', 'off'],
case_sensitive=False, default=True),
StringArgument('admin_site', required=False, default='admin'),
)
def get_context(self, context, with_labels, admin_site):
"""
Updates the *existing* context by putting a list of applicable
modeladmins into `app_list` assuming the argument `admin_site`
resolved into an AdminSite instance.
Always returns the existing context.
"""
示例5: import_taglib
def import_taglib(parser, token):
"""
Extends Django's default {% load %} templatetag as a new tag called {% import %},
which allows for extended functionality (while being backwards compatible).
Load a tag library from a particular app:
{% import myapp:mytaglib %}
Load a particular tag from a particular app:
{% import mytag from myapp:mytaglib %}
Load a particular tag from a particular app and rename:
{% import mytag from myapp:mytaglib as othername %}
**Note**: you cannot rename multiple tags, so if you do:
{% import mytag myothertag from myapp:mytaglib as othername %}
then only the last tag will be using othername, and the first one won't
be imported.
"""
bits = token.contents.split()
if (len(bits) >= 4 and bits[-2] == "from") or (len(bits) >= 6 and bits[-2] == "as"):
lib_index = -1
as_lib = None
if (bits[-2] == "as"):
lib_index = -3
as_lib = bits[-1]
try:
taglib = bits[lib_index]
lib = get_library(taglib)
except InvalidTemplateLibrary as e:
raise TemplateSyntaxError("'%s' is not a valid tag library: %s" %
(taglib, e))
else:
temp_lib = Library()
for name in bits[1:(lib_index - 1)]:
name_to_use = as_lib if as_lib else name
if name in lib.tags:
temp_lib.tags[name_to_use] = lib.tags[name]
# a name could be a tag *and* a filter, so check for both
if name in lib.filters:
temp_lib.filters[name_to_use] = lib.filters[name]
elif name in lib.filters:
temp_lib.filters[name_to_use] = lib.filters[name]
else:
raise TemplateSyntaxError("'%s' is not a valid tag or filter in tag library '%s'" %
(name, taglib))
parser.add_library(temp_lib)
else:
for taglib in bits[1:]:
# add the library to the parser
try:
lib = get_library(taglib)
parser.add_library(lib)
except InvalidTemplateLibrary as e:
raise TemplateSyntaxError("'%s' is not a valid tag library: %s" %
(taglib, e))
return LoadNode()
示例6: Library
"""
The file for a dynamic value template tag. Used originally in create locations.
"""
#pylint: disable=W0613
from django import template
from django.template.base import Library
register = Library()
class DynamicVariableNode(template.Node):
""" The Node Class for the Dynamic Value Template Tag. """
def __init__(self, form, field_string, dynamic_string):
self.form = template.Variable(form)
self.field_string = field_string
self.dynamic_string = template.Variable(dynamic_string)
def render(self, context):
try:
form = self.form.resolve(context)
dynamic_string = self.dynamic_string.resolve(context)
key = '%s%d' % (self.field_string, dynamic_string+1)
return form[key]
except template.VariableDoesNotExist:
return ''
def get_dynamic_value(parser, token):
"""
This is the name of the template tag to be called for a dynamic variable.
"""
try:
示例7: Library
from decimal import Decimal, InvalidOperation, ROUND_HALF_UP
import random as random_module
try:
from functools import wraps
except ImportError:
from django.utils.functional import wraps # Python 2.4 fallback.
from django.template.base import Variable, Library
from django.conf import settings
from django.utils import formats
from django.utils.encoding import force_unicode, iri_to_uri
from django.utils.html import conditional_escape
from django.utils.safestring import mark_safe, SafeData
from django.utils.translation import ugettext, ungettext
register = Library()
#######################
# STRING DECORATOR #
#######################
def stringfilter(func):
"""
Decorator for filters which should only receive unicode objects. The object
passed as the first positional argument will be converted to a unicode
object.
"""
def _dec(*args, **kwargs):
if args:
args = list(args)
args[0] = force_unicode(args[0])
示例8: Library
from itertools import izip_longest
from django.template.base import Library
from django.conf import settings
register = Library()
"""
for x in x_list
for x,y in xy_list
for x, y in xy_list
for x, y in xy_list reversed
for x in x_list reversed; y in y_list
for x in x_list; y in y_list reversed
"""
from django.template import Node, NodeList, Template, Context, Variable
from django.template import TemplateSyntaxError, VariableDoesNotExist
class ForNode(Node):
child_nodelists = ('nodelist_loop', 'nodelist_empty')
zip = zip
get_overall_len = min
def __init__(self, loopvars_list, sequence_list, is_reversed_list,
nodelist_loop, nodelist_empty=None, zip_func=None):
self.loopvars_list, self.sequence_list = loopvars_list, sequence_list
self.is_reversed_list = is_reversed_list
self.nodelist_loop = nodelist_loop
if nodelist_empty is None:
self.nodelist_empty = NodeList()
示例9: Library
import sys
import re
from datetime import datetime
from itertools import groupby, cycle as itertools_cycle
from django.template.base import Node, NodeList, Template, Context, Variable
from django.template.base import TemplateSyntaxError, VariableDoesNotExist, BLOCK_TAG_START, BLOCK_TAG_END, VARIABLE_TAG_START, VARIABLE_TAG_END, SINGLE_BRACE_START, SINGLE_BRACE_END, COMMENT_TAG_START, COMMENT_TAG_END
from django.template.base import get_library, Library, InvalidTemplateLibrary
from django.template.smartif import IfParser, Literal
from django.template.defaultfilters import date
from django.conf import settings
from django.utils.encoding import smart_str, smart_unicode
from django.utils.safestring import mark_safe
register = Library()
# Regex for token keyword arguments
kwarg_re = re.compile(r"(?:(\w+)=)?(.+)")
def token_kwargs(bits, parser, support_legacy=False):
"""
A utility method for parsing token keyword arguments.
:param bits: A list containing remainder of the token (split by spaces)
that is to be checked for arguments. Valid arguments will be removed
from this list.
:param support_legacy: If set to true ``True``, the legacy format
``1 as foo`` will be accepted. Otherwise, only the standard ``foo=1``
format is allowed.
示例10: Library
import types
from django.template.base import Library
from django.template.defaultfilters import stringfilter
from django.utils.encoding import force_unicode
from django.utils.safestring import mark_safe
from biogps.utils.const import species_d
register = Library()
@register.filter
@stringfilter
def html2text(value):
import html2text
return html2text.html2text(value)
#######################################################
#Taken from http://djangosnippets.org/snippets/1259/ #
#######################################################
@register.filter
def truncatesmart(value, limit=80):
"""
Truncates a string after a given number of chars keeping whole words.
Usage:
{{ string|truncatesmart }}
{{ string|truncatesmart:50 }}
"""
示例11: Library
from django.template.base import Library
register = Library()
def listStr(value):
return str(value[0])
register.filter(listStr)
示例12: Library
from django.template.base import Library, TextNode
register = Library()
def do_tag1(parser, token):
return TextNode('<app 2 lib 2 tag 1>')
def do_tag2(parser, token):
return TextNode('<app 2 lib 2 tag 2>')
register.tag('tag1', do_tag1)
register.tag('tag2', do_tag2)
示例13: import
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import logging
from classytags.arguments import Argument, StringArgument, ChoiceArgument
from classytags.core import Options
from django.template.base import Library
from classytags.helpers import InclusionTag
from django.template.defaultfilters import yesno
from adminlinks.templatetags.utils import (context_passes_test,
get_admin_site,
get_registered_modeladmins,
_admin_link_shortcut,
_add_link_to_context,
_add_custom_link_to_context)
register = Library()
logger = logging.getLogger(__name__)
class BaseAdminLink(object):
"""
Class for mixing into other classes to provide
:meth:`~adminlinks.templatetags.adminlinks_buttons.BaseAdminLink.is_valid`,
allowing subclasses to test the incoming data and react accordingly::
class MyContextHandler(BaseAdminLink):
def get_context(self, context, obj):
assert self.is_valid(context, obj) == True
Also provides
:attr:`~adminlinks.templatetags.adminlinks_buttons.BaseAdminLink.base_options`
suitable for using in classy tags.
示例14: add_library
def add_library(self, library):
wrapped_library = Library()
wrapped_library.filters = library.filters
for name, tag_compiler in library.tags.items():
wrapped_library.tags[name] = self.wrap_compile_function(name, tag_compiler)
self.parser.add_library(wrapped_library)
示例15: Library
# coding:utf-8
import os
import logging
from django.template.base import Library
from django.utils.encoding import force_text
from django.utils.safestring import mark_safe
logger = logging.getLogger(__name__)
register = Library()
def static(context, link_url):
"""
Get the path for a static file in the Cactus build.
We'll need this because paths can be rewritten with fingerprinting.
"""
# TODO: Support URLS that don't start with `/static/`
site = context['__CACTUS_SITE__']
page = context['__CACTUS_CURRENT_PAGE__']
url = site.get_url_for_static(link_url)
if url is None:
# For the static method we check if we need to add a prefix
helper_keys = [
"/static/" + link_url,
"/static" + link_url,
"static/" + link_url