Example #1
0
    def decorator(f):
        @functools.wraps(f)
        def wrapper(*args, **kw):
            if type(key_fn) is str:
                cache_key = key_fn
            else:
                cache_key = key_fn(*args, **kw)

            out = memcache.get(cache_key)
            if out is None:
                context = f(*args, **kw)
                t = get_template(template).render(context)
                out = jinja2.Markup(t)
                memcache.set(cache_key, out, expires)
            return out

        return library.global_function(wrapper)
Example #2
0
from urlobject import URLObject

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


htmlparser = HTMLParser.HTMLParser()


# Yanking filters from Django.
library.filter(defaultfilters.linebreaksbr)
library.filter(strip_tags)
library.filter(defaultfilters.timesince)
library.filter(defaultfilters.truncatewords)
library.global_function(statici18n)

library.filter(urlparams)


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


@library.global_function
def url(viewname, *args, **kwargs):
    """Helper for Django's ``reverse`` in templates."""
    locale = kwargs.pop('locale', None)
    return reverse(viewname, args=args, kwargs=kwargs, locale=locale)
Example #3
0
    helpers = HelpersNamespace()
    from shoop.front.template_helpers import general, product, category, urls

    helpers.general = general
    helpers.product = product
    helpers.category = category
    helpers.urls = urls
    for namespace in get_provide_objects("front_template_helper_namespace"):
        if namespace and getattr(namespace, "name", None):
            if callable(namespace):  # If it's a class, instantiate it
                namespace = namespace()
            setattr(helpers, namespace.name, namespace)
    return helpers


library.global_function(name="shoop", fn=SimpleLazyObject(_get_helpers))


@lru_cache()
def _cached_markdown(str_value):

    return Markdown(extensions=[
        'markdown.extensions.extra',
        'markdown.extensions.nl2br',
    ], output_format="html5").convert(str_value)


@library.filter(name="markdown")
def markdown(value):
    return mark_safe(_cached_markdown(force_text(value)))
Example #4
0

def format_datetime(value, format='medium'):
    if format == 'full':
        format = "EEEE, d. MMMM y 'at' HH:mm"
    elif format == 'medium':
        format = "EE dd.MM.y HH:mm"
    return dates.format_datetime(value, format)


from shoop.core.models import Product


def get_product_by_id(product_id):
    return Product.objects.get(pk=product_id)

library.global_function("get_product_by_id", get_product_by_id)


library.global_function("user_has_reviewed", user_has_reviewed)
library.global_function("total_review_average", total_review_average)
library.global_function("get_review_count", get_review_count)
library.global_function("get_review_average", get_review_average)
library.global_function("get_reviews", get_reviews)
library.global_function("render_category_averages", render_category_averages)
library.global_function("get_review_by_user", get_review_by_user)


library.global_function("datetime", format_datetime)

Example #5
0
from __future__ import absolute_import

from django import template

from request_vars.utils import get_variable

try:
    from django_jinja import library
except ImportError:  # pragma: no cover
    library = None

register = template.Library()

register.simple_tag(get_variable)

if library:
    library.global_function(get_variable)
Example #6
0
    helpers = HelpersNamespace()
    from E-Commerce.front.template_helpers import general, product, category, urls

    helpers.general = general
    helpers.product = product
    helpers.category = category
    helpers.urls = urls
    for namespace in get_provide_objects("front_template_helper_namespace"):
        if namespace and getattr(namespace, "name", None):
            if callable(namespace):  # If it's a class, instantiate it
                namespace = namespace()
            setattr(helpers, namespace.name, namespace)
    return helpers


library.global_function(name="E-Commerce", fn=SimpleLazyObject(_get_helpers))


@lru_cache()
def _cached_markdown(str_value):

    return Markdown(extensions=[
        'markdown.extensions.extra',
        'markdown.extensions.nl2br',
    ], output_format="html5").convert(str_value)


@library.filter(name="markdown")
def markdown(value):
    return mark_safe(_cached_markdown(force_text(value)))
Example #7
0
import jinja2

from django.utils.translation import ugettext
from django_jinja import library

from olympia.amo.utils import chunked

from .. import buttons


library.global_function(buttons.install_button)
library.global_function(buttons.big_install_button)


@library.filter
@jinja2.contextfilter
def statusflags(context, addon):
    """unreviewed/featuredaddon status flags for use as CSS classes"""
    app = context['APP']
    lang = context['LANG']
    if addon.is_unreviewed():
        return 'unreviewed'
    elif addon.is_featured(app, lang):
        return 'featuredaddon'
    else:
        return ''


@library.filter
@jinja2.contextfilter
def flag(context, addon):
Example #8
0
from django_jinja import library
from babel.support import Format

from olympia.lib.jingo_minify_helpers import (
    _build_html, _get_compiled_css_url, get_path, is_external,
    get_js_urls, get_css_urls)

from olympia import amo
from olympia.amo import utils, urlresolvers
from olympia.constants.licenses import PERSONA_LICENSES_IDS

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

# Mark a lazy marked instance as safe but keep
# it lazy
mark_safe_lazy = lazy(mark_safe, unicode)


@library.global_function
def switch_is_active(switch_name):
    return waffle.switch_is_active(switch_name)


@library.filter
def link(item):
    html = """<a href="%s">%s</a>""" % (item.get_url_path(),
Example #9
0
        logger.warning('view `%s` is not registered' % name)
    url = reverse('ssi_views:router', kwargs={'name': name})
    return format_html('<!--# include virtual="{}" -->', url)


if jinja2 is not None:
    from jinja2 import nodes
    from jinja2.ext import Extension

    class SSIIncludeExtension(Extension):
        tags = {'ssi_include'}

        def parse(self, parser):
            lineno = next(parser.stream).lineno
            view_name = parser.parse_expression()
            call = self.call_method('_ssi_include', [view_name])
            return nodes.Output([call], lineno=lineno)

        @staticmethod
        def _ssi_include(view_name):
            return do_ssi_include(view_name)

    # django-jinja support
    try:
        from django_jinja import library
    except ImportError:
        pass
    else:
        library.global_function(name='ssi_url')(do_ssi_url)
        library.extension(SSIIncludeExtension)
Example #10
0
# -*- coding: utf-8 -*-
# This file is part of E-Commerce.
#
# Copyright (c) 2012-2019, Shoop Commerce Ltd. All rights reserved.
#
# This source code is licensed under the OSL-3.0 license found in the
# LICENSE file in the root directory of this source tree.

from bootstrap3.renderers import FormRenderer
from django.utils.safestring import mark_safe
from django_jinja import library

from E-Commerce.admin.template_helpers import \
    E-Commerce_admin as E-Commerce_admin_template_helpers
from E-Commerce.admin.utils.bs3_renderers import AdminFieldRenderer


class Bootstrap3Namespace(object):
    def field(self, field, **kwargs):
        if not field:
            return ""
        return mark_safe(AdminFieldRenderer(field, **kwargs).render())

    def form(self, form, **kwargs):
        return mark_safe(FormRenderer(form, **kwargs).render())


library.global_function(name="E-Commerce_admin", fn=E-Commerce_admin_template_helpers)
library.global_function(name="bs3", fn=Bootstrap3Namespace())
Example #11
0
# -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2019, Shoop Commerce Ltd. All rights reserved.
#
# This source code is licensed under the OSL-3.0 license found in the
# LICENSE file in the root directory of this source tree.
from django_jinja import library

from shuup.gdpr.utils import get_active_consent_pages


class GDPRNamespace(object):
    def is_enabled(self, request, **kwargs):
        from shuup.gdpr.models import GDPRSettings
        return GDPRSettings.get_for_shop(request.shop).enabled

    def get_documents(self, request, **kwargs):
        return get_active_consent_pages(request.shop)


library.global_function(name="gdpr", fn=GDPRNamespace())
Example #12
0
from django import template

from django_sequential_pagination.pagination import paginate as do_paginate
from django_sequential_pagination.settings import PER_PAGE, KEY

register = template.Library()


@register.simple_tag(takes_context=True)
def paginate(context, objects, per_page=PER_PAGE, key=KEY):
	"""
	{% paginate objects 10 as page %}
	TODO: test this.
	"""
	return do_paginate(context['request'], objects, per_page, key=key)


try:
	import jinja2
except ImportError:
	pass
else:
	jinja2.contextfunction(paginate)

try:
	from django_jinja import library
except ImportError:
	pass
else:
	library.global_function(paginate)
    import jinja2
except ImportError:
    jinja2 = None

register = Library()


@register.simple_tag(takes_context=True, name='paper_cloudinary_url')
def do_paper_cloudinary_url(context, source, options_dict=None, **options):
    return paper_cloudinary_url(context, source, options_dict, **options)


if jinja2 is not None:

    class CloudinaryExtension(StandaloneTag):
        tags = {'paper_cloudinary_url'}

        def render(self, *args, **kwargs):
            return paper_cloudinary_url(self.context, *args, **kwargs)

    # django-jinja support
    try:
        from django_jinja import library
    except ImportError:
        pass
    else:
        dummy_ctx = {}
        cloudinary_url = partial(paper_cloudinary_url, dummy_ctx)
        library.global_function(name='paper_cloudinary_url')(cloudinary_url)
        library.extension(CloudinaryExtension)
			asset_sources += get_asset_sources(asset, unused, asset_type, render)
		else:
			asset_sources += get_asset_sources(asset, unused, asset_type, render)
	return "".join(asset_sources)


@register.simple_tag(takes_context=True)
def assets_js(context, *asset_list):
	return mark_safe(assets_by_type(context, "js", *asset_list))


@register.simple_tag(takes_context=True)
def assets_css(context, *asset_list):
	return mark_safe(assets_by_type(context, "css", *asset_list))


@register.simple_tag(takes_context=True)
def assets(context, *asset_list):
	return mark_safe(assets_css(context, *asset_list) + assets_js(context, *asset_list))


try:
	from django_jinja import library
	from jinja2 import contextfunction

	library.global_function(contextfunction(assets_js))
	library.global_function(contextfunction(assets_css))
	library.global_function(contextfunction(assets))
except ImportError:
	pass
Example #15
0
from ..urlresolvers import reverse, split_path
from ..utils import (format_date_time, is_beta, is_untrusted, order_params,
                     urlparams)


htmlparser = html_parser.HTMLParser()


# Yanking filters from Django.
library.filter(defaultfilters.escapejs)
library.filter(defaultfilters.linebreaksbr)
library.filter(strip_tags)
library.filter(defaultfilters.truncatewords)
library.filter(urlparams)
library.global_function(statici18n)


library.global_function(is_beta)
library.global_function(is_untrusted)


@library.global_function(name='assert')
def assert_function(statement, message=None):
    """Add runtime assertions to Jinja2 templates."""
    if not statement:
        if message:
            raise RuntimeError('Failed assertion: {}'.format(message))
        else:
            raise RuntimeError('Failed assertion')
    return ''
Example #16
0
    helpers = HelpersNamespace()
    from shuup.front.template_helpers import general, product, category, urls

    helpers.general = general
    helpers.product = product
    helpers.category = category
    helpers.urls = urls
    for namespace in get_provide_objects("front_template_helper_namespace"):
        if namespace and getattr(namespace, "name", None):
            if callable(namespace):  # If it's a class, instantiate it
                namespace = namespace()
            setattr(helpers, namespace.name, namespace)
    return helpers


library.global_function(name="shuup", fn=SimpleLazyObject(_get_helpers))


@lru_cache()
def _cached_markdown(str_value):

    return Markdown(extensions=[
        'markdown.extensions.extra',
        'markdown.extensions.nl2br',
    ], output_format="html5").convert(str_value)


@library.filter(name="markdown")
def markdown(value):
    return mark_safe(_cached_markdown(force_text(value)))
Example #17
0
@register.simple_tag(name='ajax_views_json')
def ajax_views_json():
    return mark_safe(registry_to_json())


if jinja2 is not None:
    from jinja2 import nodes
    from jinja2.ext import Extension

    class AjaxViewsExtension(Extension):
        tags = {'ajax_views_json'}

        def parse(self, parser):
            lineno = next(parser.stream).lineno
            return nodes.CallBlock(
                self.call_method('_ajax_views_json'), [], [], []
            ).set_lineno(lineno)

        @staticmethod
        def _ajax_views_json(caller):
            return registry_to_json()

    # django-jinja support
    try:
        from django_jinja import library
    except ImportError:
        pass
    else:
        library.global_function(name='ajax_url')(do_ajax_url)
        library.extension(AjaxViewsExtension)
Example #18
0
from django_jinja import library

from ..utils import allow_add_attachment_by


library.global_function(allow_add_attachment_by)
Example #19
0
from django_jinja import library

from ..utils import favicon_url

library.global_function(favicon_url)
Example #20
0
from django_jinja import library

from olympia import amo
from olympia.amo import urlresolvers, utils
from olympia.constants.licenses import PERSONA_LICENSES_IDS
from olympia.lib.jingo_minify_helpers import (
    _build_html, _get_compiled_css_url, get_css_urls, get_js_urls, get_path,
    is_external)
from olympia.lib.cache import cached


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

# Mark a lazy marked instance as safe but keep
# it lazy
mark_safe_lazy = lazy(mark_safe, unicode)


@library.global_function
def switch_is_active(switch_name):
    return waffle.switch_is_active(switch_name)


@library.filter
def link(item):
    html = """<a href="%s">%s</a>""" % (item.get_url_path(),
Example #21
0
)


class StripeNamespace(object):
    @contextfunction
    def get_saved_card_message(self, context):
        custom_message = get_saved_card_message(context["request"].shop)
        if strip_tags(custom_message).strip():
            return custom_message

    @contextfunction
    def get_checkout_payment_phase_message(self, context):
        custom_message = get_checkout_payment_phase_message(context["request"].shop)
        if strip_tags(custom_message).strip():
            return custom_message

    @contextfunction
    def get_checkout_payment_details_message(self, context):
        custom_message = get_checkout_payment_details_message(context["request"].shop)
        if strip_tags(custom_message).strip():
            return custom_message

    @contextfunction
    def get_checkout_saved_card_message(self, context):
        custom_message = get_checkout_saved_card_message(context["request"].shop)
        if strip_tags(custom_message).strip():
            return custom_message


library.global_function(name="stripe_utils", fn=StripeNamespace())
Example #22
0
class StripeNamespace(object):
    @contextfunction
    def get_saved_card_message(self, context):
        custom_message = get_saved_card_message(context["request"].shop)
        if strip_tags(custom_message).strip():
            return custom_message

    @contextfunction
    def get_checkout_payment_phase_message(self, context):
        custom_message = get_checkout_payment_phase_message(
            context["request"].shop)
        if strip_tags(custom_message).strip():
            return custom_message

    @contextfunction
    def get_checkout_payment_details_message(self, context):
        custom_message = get_checkout_payment_details_message(
            context["request"].shop)
        if strip_tags(custom_message).strip():
            return custom_message

    @contextfunction
    def get_checkout_saved_card_message(self, context):
        custom_message = get_checkout_saved_card_message(
            context["request"].shop)
        if strip_tags(custom_message).strip():
            return custom_message


library.global_function(name="stripe_utils", fn=StripeNamespace())
Example #23
0
from django_jinja import library

from ..utils import allow_add_attachment_by, attachments_payload

library.global_function(allow_add_attachment_by)
library.global_function(attachments_payload)
Example #24
0
def unicode_to_html(text):
    """Turns all unicode into html entities, e.g. &#69; -> E."""
    return ''.join([u'&#%s;' % ord(i) for i in text])


@library.global_function
def user_list(users):
    """Turn a list of users into a list of links to their profiles."""
    link = u'<a href="%s">%s</a>'
    list = u', '.join([link % (escape(u.get_absolute_url()), escape(u.username)) for
                       u in users])
    return Markup(list)


# Returns a string representation of a user
library.global_function(user_display)

# Returns a list of social authentication providers.
library.global_function(get_providers)


@library.global_function
@contextfunction
def provider_login_url(context, provider_id, **params):
    """
    {{ provider_login_url("github", next="/some/url") }}
    """
    request = context['request']
    provider = providers.registry.by_id(provider_id)
    auth_params = params.get('auth_params', None)
    scope = params.get('scope', None)
Example #25
0
    if len(export_patterns) == 1 and isinstance(export_patterns[0],
                                                (list, tuple)):
        export_patterns = export_patterns[0]
    export_patterns = frozenset(export_patterns)
    if export_patterns in js_urlpatterns.cache:
        return js_urlpatterns.cache[export_patterns]
    if export_patterns:
        url_patterns = {
            pattern['name']: pattern['patterns']
            for pattern in prepare_url_list(url_resolver)
            if pattern['name'] in export_patterns
        }
    else:
        url_patterns = {
            pattern['name']: pattern['patterns']
            for pattern in prepare_url_list(url_resolver)
        }
    js_urlpatterns.cache[export_patterns] = safe_json_str(
        json.dumps(url_patterns))
    return js_urlpatterns.cache[export_patterns]


js_urlpatterns.cache = {}

try:
    from django_jinja import library

    library.global_function(js_urlpatterns)
except ImportError:
    pass
Example #26
0
from pytz import timezone, utc
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
from ..utils import urlparams

htmlparser = HTMLParser.HTMLParser()

# Yanking filters from Django.
library.filter(defaultfilters.linebreaksbr)
library.filter(strip_tags)
library.filter(defaultfilters.truncatewords)
library.global_function(statici18n)

library.filter(urlparams)


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


@library.global_function
def url(viewname, *args, **kwargs):
    """Helper for Django's ``reverse`` in templates."""
    locale = kwargs.pop('locale', None)
    return reverse(viewname, args=args, kwargs=kwargs, locale=locale)
Example #27
0
"""
Register functions from django-browserid since we don't use Jinjo
"""
from django_browserid.helpers import (
    browserid_info,
    browserid_login,
    browserid_logout,
)
from django_jinja import library

library.global_function(browserid_info)
library.global_function(browserid_login)
library.global_function(browserid_logout)
Example #28
0
# -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2016, Shoop Commerce Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.

from bootstrap3.renderers import FormRenderer
from django.utils.safestring import mark_safe
from django_jinja import library

from shuup.admin.template_helpers import shuup_admin as shuup_admin_template_helpers
from shuup.admin.utils.bs3_renderers import AdminFieldRenderer


class Bootstrap3Namespace(object):
    def field(self, field, **kwargs):
        if not field:
            return ""
        return mark_safe(AdminFieldRenderer(field, **kwargs).render())

    def form(self, form, **kwargs):
        return mark_safe(FormRenderer(form, **kwargs).render())


library.global_function(name="shuup_admin", fn=shuup_admin_template_helpers)
library.global_function(name="bs3", fn=Bootstrap3Namespace())

@register.simple_tag(takes_context=True)
def assets_js(context, *asset_list):
    return mark_safe(assets_by_type(context, "js", *asset_list))


@register.simple_tag(takes_context=True)
def assets_css(context, *asset_list):
    return mark_safe(assets_by_type(context, "css", *asset_list))


@register.simple_tag(takes_context=True)
def assets(context, *asset_list):
    return mark_safe(
        assets_css(context, *asset_list) + assets_js(context, *asset_list))


try:
    from django_jinja import library
    try:
        from jinja2 import pass_context
    except ImportError:
        from jinja2 import contextfunction as pass_context

    library.global_function(pass_context(assets_js))
    library.global_function(pass_context(assets_css))
    library.global_function(pass_context(assets))
except ImportError:
    pass
Example #30
0
#
# This source code is licensed under the OSL-3.0 license found in the
# LICENSE file in the root directory of this source tree.
from django_jinja import library
import jinja2
import json

from django.conf import settings

from shuup.gdpr.utils import get_active_consent_pages


class GDPRNamespace(object):
    def is_enabled(self, request, **kwargs):
        from shuup.gdpr.models import GDPRSettings
        return GDPRSettings.get_for_shop(request.shop).enabled

    def get_documents(self, request, **kwargs):
        return get_active_consent_pages(request.shop)

    @jinja2.contextfunction
    def get_accepted_cookies(self, context, **kwargs):
        request = context["request"]
        if settings.SHUUP_GDPR_CONSENT_COOKIE_NAME in request.COOKIES:
            consent_cookies = request.COOKIES[settings.SHUUP_GDPR_CONSENT_COOKIE_NAME]
            return json.loads(consent_cookies).get("cookies")
        return []


library.global_function(name="gdpr", fn=GDPRNamespace())
Example #31
0
    if request is None:
        raise Exception('Make sure you have "django.core.context_processors.request" in "TEMPLATE_CONTEXT_PROCESSORS"')

    rating = Rating.objects.for_instance(item)
    if request.user.is_authenticated():
        user_rating = UserRating.objects.for_instance_by_user(item, request.user)
    else:
        user_rating = None

    stars = [i for i in range(1, STAR_RATINGS_RANGE + 1)]
    if user_rating is not None:
        user_rating_percentage = 100 * (user_rating.score * 0.2)
    else:
        user_rating_percentage = None

    return {
        'rating': rating,
        'request': request,
        'user': request.user,
        'user_rating': user_rating,
        'user_rating_percentage': user_rating_percentage,
        'stars': stars,
        'star_count': STAR_RATINGS_RANGE,
        'percentage': 100 * (rating.average / Decimal(STAR_RATINGS_RANGE)),
        'icon_height': icon_height,
        'icon_width': icon_width,
        'id': 'dsr{}'.format(uuid.uuid4().hex)
    }

library.global_function("ratings", ratings)
    def inline_wafflejs_helper(context):
        return _generate_waffle_js(context['request'])
except ImportError:
    flag_helper = None
    inline_wafflejs_helper = None


helpers = {
    'flag': flag_helper,
    'switch': switch_is_active,
    'sample': sample_is_active,
    'wafflejs': inline_wafflejs_helper
}

try:
    import jingo

    jingo.env.globals['waffle'] = helpers
except ImportError:
    # jingo isn't being used. Move on.
    pass


try:
    from django_jinja.library import global_function

    global_function('waffle', helpers)
except ImportError:
    # django-jinja isn't being used. Move on.
    pass
Example #33
0
from django import template
register = template.Library()

from .. import sr as sr_func

@register.simple_tag(name='sr')
def sr_tag(key, *args, **kwargs):
    return sr_func(key, *args, **kwargs)


try:
    from django_jinja import library as jinja_library
    jinja_library.global_function("sr", sr_func)
except ImportError:
    pass
Example #34
0
from django.utils.translation import ugettext, ungettext

import jinja2

from django_jinja import library

from olympia import amo
from olympia.access import acl
from olympia.activity.models import ActivityLog
from olympia.activity.utils import filter_queryset_to_pending_replies
from olympia.addons.templatetags.jinja_helpers import new_context
from olympia.amo.templatetags.jinja_helpers import format_date, page_title
from olympia.files.models import File


library.global_function(acl.check_addon_ownership)


@library.global_function
@library.render_with('devhub/addons/listing/items.html')
@jinja2.contextfunction
def dev_addon_listing_items(context, addons, src=None, notes=None):
    if notes is None:
        notes = {}
    return new_context(**locals())


@library.global_function
@jinja2.contextfunction
def dev_page_title(context, title=None, addon=None):
    """Wrapper for devhub page titles."""
Example #35
0
import jinja2

from django.utils.translation import ugettext
from django_jinja import library

from olympia.amo.utils import chunked
from olympia.constants.payments import PAYPAL_MAX_COMMENT_LENGTH

from .. import buttons


library.global_function(buttons.install_button)
library.global_function(buttons.big_install_button)


@library.filter
@jinja2.contextfilter
def statusflags(context, addon):
    """unreviewed/featuredaddon status flags for use as CSS classes"""
    app = context['APP']
    lang = context['LANG']
    if addon.is_unreviewed():
        return 'unreviewed'
    elif addon.is_featured(app, lang):
        return 'featuredaddon'
    else:
        return ''


@library.filter
@jinja2.contextfilter
Example #36
0
# -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2018, Shoop Commerce Ltd. All rights reserved.
#
# This source code is licensed under the OSL-3.0 license found in the
# LICENSE file in the root directory of this source tree.

from bootstrap3.renderers import FormRenderer
from django.utils.safestring import mark_safe
from django_jinja import library

from shuup.admin.template_helpers import \
    shuup_admin as shuup_admin_template_helpers
from shuup.admin.utils.bs3_renderers import AdminFieldRenderer


class Bootstrap3Namespace(object):
    def field(self, field, **kwargs):
        if not field:
            return ""
        return mark_safe(AdminFieldRenderer(field, **kwargs).render())

    def form(self, form, **kwargs):
        return mark_safe(FormRenderer(form, **kwargs).render())


library.global_function(name="shuup_admin", fn=shuup_admin_template_helpers)
library.global_function(name="bs3", fn=Bootstrap3Namespace())
Example #37
0
from babel.support import Format
from django_jinja import library
from rest_framework.reverse import reverse as drf_reverse
from rest_framework.settings import api_settings

from olympia import amo
from olympia.amo import urlresolvers, utils
from olympia.amo.reverse import get_url_prefix
from olympia.lib.jingo_minify_helpers import _build_html, get_css_urls, get_js_urls

register = Library()

# Registering some utils as filters:
library.filter(utils.isotime)
library.global_function(dict)
library.global_function(static)


@library.filter
def urlparams(*args, **kwargs):
    return markupsafe.Markup(utils.urlparams(*args, **kwargs))


@library.global_function
def switch_is_active(switch_name):
    return waffle.switch_is_active(switch_name)


@library.global_function
def locale_url(url):
Example #38
0
    return ''.join(['&#%s;' % ord(i) for i in text])


@library.global_function
def user_list(users):
    """Turn a list of users into a list of links to their profiles."""
    link = '<a href="%s">%s</a>'
    list = ', '.join([
        link % (escape(u.get_absolute_url()), escape(u.username))
        for u in users
    ])
    return Markup(list)


# Returns a string representation of a user
library.global_function(user_display)

# Returns a list of social authentication providers.
library.global_function(get_providers)


@library.global_function
@contextfunction
def provider_login_url(context, provider_id, **params):
    """
    {{ provider_login_url("github", next="/some/url") }}
    """
    request = context['request']
    provider = providers.registry.by_id(provider_id)
    auth_params = params.get('auth_params', None)
    scope = params.get('scope', None)
Example #39
0
from ..urlresolvers import reverse, split_path
from ..utils import (format_date_time, is_untrusted, is_wiki, order_params,
                     urlparams)


htmlparser = HTMLParser()


# Yanking filters from Django.
library.filter(defaultfilters.escapejs)
library.filter(defaultfilters.linebreaksbr)
library.filter(strip_tags)
library.filter(defaultfilters.truncatewords)
library.filter(urlparams)
library.global_function(statici18n)


library.global_function(is_wiki)
library.global_function(is_untrusted)


@library.global_function(name='assert')
def assert_function(statement, message=None):
    """Add runtime assertions to Jinja2 templates."""
    if not statement:
        if message:
            raise RuntimeError('Failed assertion: {}'.format(message))
        else:
            raise RuntimeError('Failed assertion')
    return ''
Example #40
0
from django import template
register = template.Library()

from .. import sr as sr_func


@register.simple_tag(name='sr')
def sr_tag(key, *args, **kwargs):
    return sr_func(key, *args, **kwargs)


try:
    from django_jinja import library as jinja_library
    jinja_library.global_function("sr", sr_func)
except ImportError:
    pass
Example #41
0
                       scope=None,
                       auth_params=None,
                       next=None):
    """Get the login URL for a socialaccount provider.

    Jingo version of provider_login_url from
    allauth/socialaccount/templatetags/socialaccount.py
    """
    provider = providers.registry.by_id(provider_id)
    query = {'process': process}
    if scope:
        query['scope'] = scope
    if auth_params:
        query['auth_params'] = auth_params
    if next:
        query['next'] = next
    else:
        next = request.POST.get('next') or request.GET.get('next')
        if next:
            query['next'] = next
        elif process == 'redirect':
            query['next'] = request.get_full_path()

    # get the login url and append query as url parameters
    return provider.get_login_url(request, **query)


library.global_function(get_providers)
library.global_function(get_social_accounts)
library.global_function(user_display)
Example #42
0
from django.utils.encoding import force_bytes
from django.utils.translation import ugettext, ungettext

import jinja2

from django_jinja import library

from olympia import amo
from olympia.access import acl
from olympia.activity.models import ActivityLog
from olympia.activity.utils import filter_queryset_to_pending_replies
from olympia.addons.templatetags.jinja_helpers import new_context
from olympia.amo.templatetags.jinja_helpers import format_date, page_title
from olympia.files.models import File

library.global_function(acl.check_addon_ownership)


@library.global_function
@library.render_with('devhub/addons/listing/items.html')
@jinja2.contextfunction
def dev_addon_listing_items(context, addons, src=None, notes=None):
    if notes is None:
        notes = {}
    return new_context(**locals())


@library.global_function
@jinja2.contextfunction
def dev_page_title(context, title=None, addon=None):
    """Wrapper for devhub page titles."""
Example #43
0
@register.filter
def is_select(field):
	return isinstance(field.field.widget, forms.Select)


@register.filter
def is_radio(field):
	return isinstance(field.field.widget, forms.RadioSelect)


@register.filter
def is_multiple(field):
	return isinstance(field.field, forms.MultipleChoiceField)


try:
	from django_jinja import library

	#library.global_function(contextfunction(formrow_template))
	library.global_function(fn=jinja_get_formlayout_template, name='get_formlayout_template')
	library.global_function(fn=jinja_get_formrow_template, name='get_formrow_template')
	library.filter(add_field_class)
	library.filter(is_checkbox)
	library.filter(is_select)
	library.filter(is_radio)
	library.filter(is_multiple)
	library.filter(add_field_attr)
except ImportError:
	pass