Esempio n. 1
0
def test_filter_override():
    def f(s):
        return s.upper()
    f.__name__ = 'a'
    register.filter(f)
    s = render('{{ s|a }}', {'s': 'Str'})
    eq_(s, 'STR')

    def g(s):
        return s.lower()
    g.__name__ = 'a'
    register.filter(override=False)(g)
    s = render('{{ s|a }}', {'s': 'Str'})
    eq_(s, 'STR')

    register.filter(g)
    s = render('{{ s|a }}', {'s': 'Str'})
    eq_(s, 'str')
Esempio n. 2
0
def test_filter_override():
    def f(s):
        return s.upper()
    # See issue 7688: http://bugs.python.org/issue7688
    f.__name__ = 'a' if six.PY3 else b'a'
    register.filter(f)
    s = render('{{ s|a }}', {'s': 'Str'})
    eq_(s, 'STR')

    def g(s):
        return s.lower()
    g.__name__ = 'a' if six.PY3 else b'a'
    register.filter(override=False)(g)
    s = render('{{ s|a }}', {'s': 'Str'})
    eq_(s, 'STR')

    register.filter(g)
    s = render('{{ s|a }}', {'s': 'Str'})
    eq_(s, 'str')
Esempio n. 3
0
def test_filter_override():
    def f(s):
        return s.upper()

    f.__name__ = 'a'
    register.filter(f)
    s = render('{{ s|a }}', {'s': 'Str'})
    eq_(s, 'STR')

    def g(s):
        return s.lower()

    g.__name__ = 'a'
    register.filter(override=False)(g)
    s = render('{{ s|a }}', {'s': 'Str'})
    eq_(s, 'STR')

    register.filter(g)
    s = render('{{ s|a }}', {'s': 'Str'})
    eq_(s, 'str')
Esempio n. 4
0
def test_filter_override():
    def f(s):
        return s.upper()

    # See issue 7688: http://bugs.python.org/issue7688
    f.__name__ = "a" if six.PY3 else b"a"
    register.filter(f)
    s = render("{{ s|a }}", {"s": "Str"})
    eq_(s, "STR")

    def g(s):
        return s.lower()

    g.__name__ = "a" if six.PY3 else b"a"
    register.filter(override=False)(g)
    s = render("{{ s|a }}", {"s": "Str"})
    eq_(s, "STR")

    register.filter(g)
    s = render("{{ s|a }}", {"s": "Str"})
    eq_(s, "str")
Esempio n. 5
0
def test_filter_override():
    def f(s):
        return s.upper()

    # See issue 7688: http://bugs.python.org/issue7688
    f.__name__ = 'a' if six.PY3 else b'a'
    register.filter(f)
    s = render('{{ s|a }}', {'s': 'Str'})
    eq_(s, 'STR')

    def g(s):
        return s.lower()

    g.__name__ = 'a' if six.PY3 else b'a'
    register.filter(override=False)(g)
    s = render('{{ s|a }}', {'s': 'Str'})
    eq_(s, 'STR')

    register.filter(g)
    s = render('{{ s|a }}', {'s': 'Str'})
    eq_(s, 'str')
Esempio n. 6
0
    url = urlparse.urlparse(url_)
    fragment = hash if hash is not None else url.fragment

    # Use dict(parse_qsl) so we don't get lists of values.
    q = url.query
    query_dict = dict(urlparse.parse_qsl(smart_str(q))) if q else {}
    query_dict.update((k, v) for k, v in query.items())

    query_string = urllib.urlencode([(k2, v2) for k2, v2 in query_dict.items()
                                     if v2 is not None])
    new = urlparse.ParseResult(url.scheme, url.netloc, url.path, url.params,
                               query_string, fragment)
    return new.geturl()


urlparams = register.filter(urlparams)


@register.filter
def prettify_obj_type(obj_type, *args, **kwargs):
    return get_klasses(obj_type)[0].pretty_type

@register.filter
def smart_capitalize(x):
    return x[0].upper() + x[1:]

@register.function
def a_or_an(next_word):
    """
    Chooses 'a' or 'an' depending on first letter of next word.
    Add in special cases if next word is 'hour' or something.
Esempio n. 7
0
import datetime
import jinja2
from jinja2.exceptions import FilterArgumentError
import pytz
import time

from jingo import register, env
from l10n import ugettext as _

import amo
from amo import urlresolvers
from addons.models import Category
from translations.query import order_by_translation

# Yanking filters from Django.
register.filter(defaultfilters.slugify)


@register.function
def locale_url(url):
    """Take a URL and give it the locale prefix."""
    prefixer = urlresolvers.get_url_prefix()
    script = prefixer.request.META['SCRIPT_NAME']
    parts = [script, prefixer.locale, url.lstrip('/')]
    return '/'.join(parts)


@register.function
def url(viewname, *args, **kwargs):
    """Helper for Django's ``reverse`` in templates."""
    return urlresolvers.reverse(viewname, args=args, kwargs=kwargs)
Esempio n. 8
0
import urllib

from django.contrib.auth.models import User
from django.template.defaultfilters import date
from django.utils.hashcompat import md5_constructor

import jinja2
from jingo import register


register.filter(date)


@register.function
def gravatar_url(arg, size=80):
    if isinstance(arg, User):
        email = arg.email
    else:  # Treat as email
        email = arg

    url = 'https://secure.gravatar.com/avatar/{0}?{1}'.format(
        md5_constructor(email.lower()).hexdigest(),
        urllib.urlencode({'s': str(size), 'default': 'mm'})
    )

    return url


@register.function
def gravatar_img(arg, size=80):
    return jinja2.Markup('<img src="%s">' % gravatar_url(arg, size=size))
Esempio n. 9
0
from django.utils import translation
from django.utils.encoding import smart_str

from babel import Locale
from babel.dates import format_datetime
from babel.support import Format
from jingo import register
import jinja2
import pytz

import utils
from .urlresolvers import reverse


# Yanking filters from Django.
register.filter(defaultfilters.iriencode)


def _get_format():
    lang = translation.get_language()
    locale = Locale(translation.to_locale(lang))
    return Format(locale)


@register.filter
def numberfmt(num, format=None):
    return _get_format().decimal(num, format)


@register.filter
def isotime(t):
Esempio n. 10
0
import waffle
from babel.support import Format
from jingo import register, get_env
# Needed to make sure our own |f filter overrides jingo's one.
from jingo import helpers  # noqa
from jingo_minify.helpers import (_build_html, _get_compiled_css_url, get_path,
                                  is_external)

from olympia import amo
from olympia.amo import utils, urlresolvers
from olympia.constants.licenses import PERSONA_LICENSES_IDS
from olympia.translations.query import order_by_translation
from olympia.translations.helpers import truncate

# Yanking filters from Django.
register.filter(defaultfilters.slugify)

# Registering some utils as filters:
urlparams = register.filter(utils.urlparams)
register.filter(utils.epoch)
register.filter(utils.isotime)
register.function(dict)
register.function(utils.randslice)


@register.function
def switch_is_active(switch_name):
    return waffle.switch_is_active(switch_name)


@register.filter
Esempio n. 11
0
from django.utils import translation
from django.utils.encoding import smart_str
from django.utils.http import urlencode

from babel import Locale, UnknownLocaleError
from babel.support import Format
from jingo import register
import jinja2
import pytz
from tower import ugettext as _, ungettext as ngettext

from .urlresolvers import reverse
from themes.helpers import new_context

# Yanking filters from Django.
register.filter(defaultfilters.iriencode)
register.filter(defaultfilters.slugify)
register.filter(defaultfilters.truncatewords)


def _get_format():
    lang = translation.get_language()
    try:
        locale = Locale(translation.to_locale(lang))
    except UnknownLocaleError:
        locale = Locale(translation.to_locale(settings.BABEL_FALLBACK.get(
            lang, 'en-US')))
    return Format(locale)


@register.filter
Esempio n. 12
0
__author__ = 'sha256'

from jingo import register
from .templatetags.form_attr import filtering, filters

for f in filters:
    register.filter(f, filtering(f))
from django.contrib.staticfiles.templatetags.staticfiles import static
from django.template.loader import render_to_string
from django.template.defaultfilters import date, pluralize, urlize
from django.conf import settings

from jingo import register
from jinja2 import Markup


static = register.function(static)
register.filter(date)
register.filter(pluralize)
register.filter(urlize)


@register.function
def field_with_attrs(bfield, **kwargs):
    """Allows templates to dynamically add html attributes to bound
    fields from django forms.

    Taken from bedrock.
    """
    bfield.field.widget.attrs.update(kwargs)
    return bfield


@register.function
def field_errors(field):
    """Return string with rendered template with field errors."""
    return Markup(render_to_string('form-error.html', {'field': field}))
Esempio n. 14
0
from django.utils.encoding import smart_str
from django.utils.http import urlencode
from django.utils.safestring import mark_safe

from babel import Locale, UnknownLocaleError
from babel.support import Format
from jingo import register
import jinja2
import pytz
from tower import ugettext as _, ungettext as ngettext

from .urlresolvers import reverse
from themes.helpers import new_context

# Yanking filters from Django.
register.filter(defaultfilters.iriencode)
register.filter(defaultfilters.slugify)
register.filter(defaultfilters.truncatewords)


def _get_format():
    lang = translation.get_language()
    try:
        locale = Locale(translation.to_locale(lang))
    except UnknownLocaleError:
        locale = Locale(
            translation.to_locale(settings.BABEL_FALLBACK.get(lang, 'en-US')))
    return Format(locale)


@register.filter
Esempio n. 15
0
from django.template import defaultfilters

from jingo import register

# Only used in admin/settings.html
register.filter(defaultfilters.slugify)
Esempio n. 16
0
        for k, v in cgi.parse_qsl(url_.query):
            items.append((k, v))
    for k, v in query.items():
        items.append((k, v))

    items = [(k, unicode(v).encode('raw_unicode_escape')) for
             k, v in items if v is not None]

    query_string = urlencode(items)

    new = urlparse.ParseResult(url_.scheme, url_.netloc, url_.path,
                               url_.params, query_string, fragment)
    return new.geturl()


wiki_to_html = register.filter(wiki_to_html)


class Paginator(object):

    def __init__(self, pager):
        self.pager = pager

        self.max = 10
        self.span = (self.max - 1) / 2

        self.page = pager.number
        self.num_pages = pager.paginator.num_pages
        self.count = pager.paginator.count

        pager.page_range = self.range()
Esempio n. 17
0
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.

from django.utils.html import escapejs
from jingo import register

#
# This is the place to register Django template filters with the jingo
# template engine. If you see a filter in the Django documentation [1]
# that is not included with Jingo then you can simply import and
# register it here as shown below.
#
# [1] https://docs.djangoproject.com/en/dev/ref/templates/builtins/
#

register.filter(escapejs)
Esempio n. 18
0
from django.template import defaultfilters
from django.utils.html import strip_tags

import bleach
from jingo import register
import jinja2
import pytz
from soapbox.models import Message

import utils
from sumo.urlresolvers import split_path, reverse
from wiki.models import Document


# Yanking filters from Django.
register.filter(strip_tags)
register.filter(defaultfilters.timesince)
register.filter(defaultfilters.truncatewords)

register.filter(utils.entity_decode)


@register.function
def page_title(title):
    return u"%s | MDN" % title


@register.filter
def isotime(t):
    """Date/Time format according to ISO 8601"""
    if not hasattr(t, "tzinfo"):
Esempio n. 19
0
from django.template.defaultfilters import \
     (addslashes, escapejs, fix_ampersands,
      floatformat, iriencode, linenumbers,
      slugify, truncatewords, truncatewords_html,
      urlencode, cut, rjust, ljust, linebreaks,
      linebreaksbr, removetags, unordered_list,
      date, time, timesince, timeuntil, yesno,
      pluralize, phone2numeric, capfirst)

for func in (addslashes, escapejs, fix_ampersands, floatformat, iriencode,
             linenumbers, slugify, truncatewords, truncatewords_html,
             urlencode, cut, rjust, ljust, linebreaks, linebreaksbr,
             removetags, unordered_list, date, time, timesince, timeuntil,
             yesno, pluralize, phone2numeric, capfirst):
    register.filter(func)


@jinja2.contextfunction
@register.function
def querystring(context, query, **params):
    """
    Add paramaters to a query string. New params will be appended, duplicates will
    be overwritten.
    """

    # separate querystring from route
    qs = []
    if context != None:
        url_parts = context['request'].get_full_path().split('?')
        qs = url_parts[1].split('&') if len(url_parts) == 2 else []
Esempio n. 20
0
@contextfunction
def trans_str(context, trans_obj):
    """Pick a translation as an unescaped string.

    The string is not wrapped in an HTML element and not marked as HTML safe.
    """
    return pick_translation(context, trans_obj)[0]


@register.function
def current_year():
    return date.today().year


@register.function
def is_debug():
    return settings.DEBUG


@register.function
def add_query_param(url, **query):
    for key, val in query.items():
        url = replace_query_param(url, key, val)
    return url


register.filter(add_class)
register.filter(urlize_quoted_links)
register.filter(break_long_headers)
register.function(static)
Esempio n. 21
0
from jingo import env, register
# Needed to make sure our own |f filter overrides jingo's one.
from jingo import helpers  # noqa
from jingo_minify import helpers as jingo_minify_helpers
from six import text_type
from tower import ugettext as _

from amo.utils import isotime, urlparams
from mkt.translations.helpers import truncate
from mkt.translations.utils import get_locale_from_lang


log = commonware.log.getLogger('z.mkt.site')

# Registering some utils as filters:
register.filter(urlparams)
register.filter(isotime)


@jinja2.contextfunction
@register.function
def css(context, bundle, media=False, debug=None):
    if debug is None:
        debug = settings.TEMPLATE_DEBUG

    # ?debug=true gives you unminified CSS for testing on -dev/prod.
    if context['request'].GET.get('debug'):
        debug = True

    return jingo_minify_helpers.css(bundle, media, debug)
Esempio n. 22
0
    rjust,
    ljust,
    linebreaks,
    linebreaksbr,
    removetags,
    unordered_list,
    date,
    time,
    timesince,
    timeuntil,
    yesno,
    pluralize,
    phone2numeric,
    capfirst,
):
    register.filter(func)


@jinja2.contextfunction
@register.function
def querystring(context, query, **params):
    """
    Add paramaters to a query string. New params will be appended, duplicates will
    be overwritten.
    """

    # separate querystring from route
    qs = []
    if context != None:
        url_parts = context["request"].get_full_path().split("?")
        qs = url_parts[1].split("&") if len(url_parts) == 2 else []
Esempio n. 23
0
File: helpers.py Progetto: gerv/kuma
from django.template import defaultfilters
from django.utils.html import strip_tags

import bleach
from jingo import register
import jinja2
import pytz
from soapbox.models import Message

import utils
from sumo.urlresolvers import split_path, reverse
from wiki.models import Document


# Yanking filters from Django.
register.filter(strip_tags)
register.filter(defaultfilters.timesince)
register.filter(defaultfilters.truncatewords)

register.filter(utils.entity_decode)


@register.function
def page_title(title):
    return u'%s | MDN' % title


@register.filter
def isotime(t):
    """Date/Time format according to ISO 8601"""
    if not hasattr(t, 'tzinfo'):
Esempio n. 24
0
    return getattr(obj, value, default)


@register.filter
def absolutify(url):
    """Prepend the SITE_URL to the url."""
    return utils.absolutify(url)


@register.function
def get_date_n_weeks_before(date, weeks=0):
    """Return the date X weeks before date."""
    return date - timedelta(weeks=weeks)


@register.filter
def formset_errors_exist(formset):
    for form in formset.values():
        if form.errors:
            return True
    return False


@register.filter
def get_country_code(country_name):
    """Return country code from country name."""
    return COUNTRIES_NAME_TO_CODE.get(country_name.lower(), '')


register.filter(pluralize)
Esempio n. 25
0
    url = urlparse.urlparse(url_)
    fragment = hash if hash is not None else url.fragment

    # Use dict(parse_qsl) so we don't get lists of values.
    q = url.query
    query_dict = dict(urlparse.parse_qsl(smart_str(q))) if q else {}
    query_dict.update((k, v) for k, v in query.items())

    query_string = urllib.urlencode([(k2, v2) for k2, v2 in query_dict.items()
                                     if v2 is not None])
    new = urlparse.ParseResult(url.scheme, url.netloc, url.path, url.params,
                               query_string, fragment)
    return new.geturl()


urlparams = register.filter(urlparams)


@register.filter
def prettify_obj_type(obj_type, *args, **kwargs):
    return get_klasses(obj_type)[0].pretty_type


@register.filter
def smart_capitalize(x):
    return x[0].upper() + x[1:]


@register.function
def a_or_an(next_word):
    """
Esempio n. 26
0
from babel.support import Format
from jingo import register, env
# Needed to make sure our own |f filter overrides jingo's one.
from jingo import helpers  # noqa
from tower import ugettext as _, strip_whitespace

import amo
from amo import urlresolvers, utils
from constants.licenses import PERSONA_LICENSES_IDS
from translations.helpers import truncate
from translations.query import order_by_translation
from versions.models import License


# Yanking filters from Django.
register.filter(defaultfilters.slugify)

# Registering some utils as filters:
urlparams = register.filter(utils.urlparams)
register.filter(utils.epoch)
register.filter(utils.isotime)
register.function(dict)
register.function(utils.randslice)


@register.filter
def link(item):
    html = """<a href="%s">%s</a>""" % (item.get_url_path(),
                                        jinja2.escape(item.name))
    return jinja2.Markup(html)
Esempio n. 27
0
    return getattr(obj, value, default)


@register.filter
def absolutify(url):
    """Prepend the SITE_URL to the url."""
    return utils.absolutify(url)


@register.function
def get_date_n_weeks_before(date, weeks=0):
    """Return the date X weeks before date."""
    return date - timedelta(weeks=weeks)


@register.filter
def formset_errors_exist(formset):
    for form in formset.values():
        if form.errors:
            return True
    return False


@register.filter
def get_country_code(country_name):
    """Return country code from country name."""
    return COUNTRIES_NAME_TO_CODE.get(country_name.lower(), '')


register.filter(pluralize)
Esempio n. 28
0
from django.utils.translation import ungettext
from jingo import env, register
from pytz import timezone
from soapbox.models import Message
from statici18n.templatetags.statici18n import statici18n
from urlobject import URLObject

from .exceptions import DateTimeFormatError
from .urlresolvers import reverse, split_path


htmlparser = HTMLParser.HTMLParser()


# Yanking filters from Django and 3rd party libs.
register.filter(strip_tags)
register.filter(defaultfilters.timesince)
register.filter(defaultfilters.truncatewords)
register.function(statici18n)


@register.filter
def paginator(pager):
    """Render list of pages."""
    return Paginator(pager).render()


@register.function
def url(viewname, *args, **kwargs):
    """Helper for Django's ``reverse`` in templates."""
    locale = kwargs.pop('locale', None)
Esempio n. 29
0
from babel.support import Format
from jingo import env, register
# Needed to make sure our own |f filter overrides jingo's one.
from jingo import helpers  # noqa
from jingo_minify import helpers as jingo_minify_helpers
from six import text_type
from tower import ugettext as _

from amo.utils import isotime, urlparams
from mkt.translations.helpers import truncate
from mkt.translations.utils import get_locale_from_lang

log = commonware.log.getLogger('z.mkt.site')

# Registering some utils as filters:
register.filter(urlparams)
register.filter(isotime)


@jinja2.contextfunction
@register.function
def css(context, bundle, media=False, debug=None):
    if debug is None:
        debug = settings.TEMPLATE_DEBUG

    # ?debug=true gives you unminified CSS for testing on -dev/prod.
    if context['request'].GET.get('debug'):
        debug = True

    return jingo_minify_helpers.css(bundle, media, debug)