Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added new filters for templates #18125

Merged
merged 3 commits into from
Dec 1, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions homeassistant/helpers/template.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import logging
import math
import random
import base64
import re

import jinja2
Expand Down Expand Up @@ -602,6 +603,23 @@ def bitwise_or(first_value, second_value):
return first_value | second_value


def base64_encode(value):
"""Perform base64 encode."""
return base64.b64encode(value.encode('utf-8')).decode('utf-8')


def base64_decode(value):
"""Perform base64 denode."""
return base64.b64decode(value).decode('utf-8')


def ordinal(value):
"""Perform ordinal conversion."""
return str(value) + (list(['th', 'st', 'nd', 'rd'] + ['th'] * 6)
[(int(str(value)[-1])) % 10] if not
int(str(value)[-2:]) % 100 in range(11, 14) else 'th')


@contextfilter
def random_every_time(context, values):
"""Choose a random value.
Expand Down Expand Up @@ -640,6 +658,9 @@ def is_safe_attribute(self, obj, attr, value):
ENV.filters['max'] = max
ENV.filters['min'] = min
ENV.filters['random'] = random_every_time
ENV.filters['base64_encode'] = base64_encode
ENV.filters['base64_decode'] = base64_decode
ENV.filters['ordinal'] = ordinal
ENV.filters['regex_match'] = regex_match
ENV.filters['regex_replace'] = regex_replace
ENV.filters['regex_search'] = regex_search
Expand Down
31 changes: 31 additions & 0 deletions tests/helpers/test_template.py
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,37 @@ def test_max(self):
template.Template('{{ [1, 2, 3] | max }}',
self.hass).render()

def test_base64_encode(self):
"""Test the base64_encode filter."""
self.assertEqual(
'aG9tZWFzc2lzdGFudA==',
template.Template('{{ "homeassistant" | base64_encode }}',
self.hass).render())

def test_base64_decode(self):
"""Test the base64_decode filter."""
self.assertEqual(
'homeassistant',
template.Template('{{ "aG9tZWFzc2lzdGFudA==" | base64_decode }}',
self.hass).render())

def test_ordinal(self):
"""Test the ordinal filter."""
tests = [
(1, '1st'),
(2, '2nd'),
(3, '3rd'),
(4, '4th'),
(5, '5th'),
]

for value, expected in tests:
self.assertEqual(
expected,
template.Template(
'{{ %s | ordinal }}' % value,
self.hass).render())

def test_timestamp_utc(self):
"""Test the timestamps to local filter."""
now = dt_util.utcnow()
Expand Down