Skip to content

base64_url_safe_encode

The base64_url_safe_encode filter encodes a string using the URL-safe Base64 format. This is a variation of the standard Base64 encoding that is specifically designed to be safe for use in URLs and file names.

Functionality

  • Strings: Takes a string as input.
  • Encoding: Converts the input string into a URL-safe Base64 representation.
  • URL-Safe Modifications: Replaces the characters '+' and '/' (which are not URL-safe) with '-' and '_', respectively.
  • Output: Returns a new string containing the URL-safe Base64 encoded data.

Syntax

    {{ input_string | base64_url_safe_encode }}
Arguments

The base64_url_safe_encode filter does not require any arguments.

Code Samples

Example 1: Encoding a String

    {% assign data = "Hello, world!" %}

    {{ data | base64_url_safe_encode }}
Output:
SGVsbG8sIHdvcmxkIQ==
Example 2: Encoding Binary Data

    {% assign binary_data = "This is some binary data." | binary_encode %}

    {{ binary_data | base64_url_safe_encode }}

Output:

VGhpcyBpcyBzb21lIGJpbmFyeSBkYXRhLg==

Outliers and Special Cases

  • Empty Strings: If the input string is empty, the base64_url_safe_encode filter returns an empty string.
  • Non-String Input: If the input is not a string, the filter might attempt to convert it to a string or return an error.

Key Points

  • The base64_url_safe_encode filter is essential when you need to include binary data or characters that are not URL-safe within a URL or file name.
  • It is commonly used in conjunction with its counterpart, base64_url_safe_decode, to transmit or store data securely while maintaining URL compatibility.
  • The output of the filter will always be a string containing only URL-safe characters (alphanumeric, '-', and '_').