Base64 Encoding in Templates

Hello HASS hackers,

How can I convert to base 64 in a template?

I seem to remember the following template working:

{% set x = "test" | b64encode %}
{{x}}

But no dice!

I went to “Developer Tools->Template” and punched it in, only to be met with an error:

TemplateAssertionError: No filter named ‘b64encode’.

Can anyone help me out here? Is there another way?
I’m trying to make a REST sensor and need base64 in the URL.

Thanks,
Joshua

Nevermind I figured it out.

This seems to work:

{% set x = "test" | base64_encode | replace('+', '-') | replace('/', '_') | replace('=', '') %}
{{x}}

It doesn’t seem to be too well documented, I couldn’t find it anywhere on the Jinja2 documentation.
No doubt someone will link to it and make me look quite foolish now I’ve said that!

Worse… there are a lot of wrong answers about using b64encode because of an unrelated Jinja extension.

However, I did find a base64_decode function mentioned on the Home Assistant wiki’s template page.

Sure enough, this implies the existence of base64_encode.

Not the URL-safe version (like Python’s base64.urlsafe_b64encode function).
But that’s nothing a few replace() filters can’t fix.
(I also had to remove the equals signs because of the target URL format)

I’ll leave this here just in case anyone else is looking for this.

1 Like

Could you also mark your own post as the solution so it is visible there is an answer? Thanks!