예제 #1
0
def do_replace(s, old, new, count=None):
    """
    Return a copy of the value with all occurrences of a substring
    replaced with a new one. The first argument is the substring
    that should be replaced, the second is the replacement string.
    If the optional third argument ``count`` is given, only the first
    ``count`` occurrences are replaced:

    .. sourcecode:: jinja

        {{ "Hello World"|replace("Hello", "Goodbye") }}
            -> Goodbye World

        {{ "aaaaargh"|replace("a", "d'oh, ", 2) }}
            -> d'oh, d'oh, aaargh
    """
    if not isinstance(old, basestring) or \
       not isinstance(new, basestring):
        raise FilterArgumentError('the replace filter requires '
                                  'string replacement arguments')
    if count is None:
        return s.replace(old, new)
    if not isinstance(count, (int, long)):
        raise FilterArgumentError('the count parameter of the '
                                  'replace filter requires '
                                  'an integer')
    return s.replace(old, new, count)
예제 #2
0
def do_capture(name='captured', clean=False):
    """
    Store the value in a variable called ``captured`` or a variable
    with the name provided. Useful for filter blocks:

    .. sourcecode:: jinja

        {% filter capture('foo') %}
            ...
        {% endfilter %}
        {{ foo }}

    This will output "..." two times. One time from the filter block
    and one time from the variable. If you don't want the filter to
    output something you can use it in `clean` mode:

    .. sourcecode:: jinja

        {% filter capture('foo', True) %}
            ...
        {% endfilter %}
        {{ foo }}
    """
    if not isinstance(name, basestring):
        raise FilterArgumentError('You can only capture into variables')

    def wrapped(env, context, value):
        context[name] = value
        if clean:
            return TemplateData()
        return value

    return wrapped
예제 #3
0
def do_round(precision=0, method='common'):
    """
    Round the number to a given precision. The first
    parameter specifies the precision (default is ``0``), the
    second the rounding method:

    - ``'common'`` rounds either up or down
    - ``'ceil'`` always rounds up
    - ``'floor'`` always rounds down

    If you don't specify a method ``'common'`` is used.

    .. sourcecode:: jinja

        {{ 42.55|round }}
            -> 43
        {{ 42.55|round(1, 'floor') }}
            -> 42.5

    *new in Jinja 1.1*
    """
    if not method in ('common', 'ceil', 'floor'):
        raise FilterArgumentError('method must be common, ceil or floor')
    if precision < 0:
        raise FilterArgumentError('precision must be a postive integer '
                                  'or zero.')

    def wrapped(env, context, value):
        if method == 'common':
            return round(value, precision)
        import math
        func = getattr(math, method)
        if precision:
            return func(value * 10 * precision) / (10 * precision)
        else:
            return func(value)

    return wrapped
예제 #4
0
def do_dformat(d):
    """
    Apply python mapping string formatting on an object:

    .. sourcecode:: jinja

        {{ "Hello %(username)s!"|dformat({'username': '******'}) }}
            -> Hello John Doe!

    This is useful when adding variables to translateable
    string expressions.

    *New in Jinja 1.1*
    """
    if not isinstance(d, dict):
        raise FilterArgumentError('dict required')
    def wrapped(env, context, value):
        return env.to_unicode(value) % d
    return wrapped
예제 #5
0
def do_dictsort(case_sensitive=False, by='key'):
    """
    Sort a dict and yield (key, value) pairs. Because python dicts are
    unsorted you may want to use this function to order them by either
    key or value:

    .. sourcecode:: jinja

        {% for item in mydict|dictsort %}
            sort the dict by key, case insensitive

        {% for item in mydict|dicsort(true) %}
            sort the dict by key, case sensitive

        {% for item in mydict|dictsort(false, 'value') %}
            sort the dict by key, case insensitive, sorted
            normally and ordered by value.
    """
    if by == 'key':
        pos = 0
    elif by == 'value':
        pos = 1
    else:
        raise FilterArgumentError('You can only sort by either '
                                  '"key" or "value"')

    def sort_func(value, env):
        if isinstance(value, basestring):
            value = env.to_unicode(value)
            if not case_sensitive:
                value = value.lower()
        return value

    def wrapped(env, context, value):
        items = value.items()
        items.sort(
            lambda a, b: cmp(sort_func(a[pos], env), sort_func(b[pos], env)))
        return items

    return wrapped