Skip to content

base64_decode

The base64_decode filter is specifically designed to decode strings that have been encoded using the Base64 format. Base64 encoding is a common way to represent binary data (such as images or files) using a set of 64 printable ASCII characters, making it suitable for transmission over text-based protocols.

Functionality

  • Strings: Takes a string encoded in Base64 format as input.
  • Decoding: Converts the Base64 string back into its original binary data representation.
  • Output: Returns a string containing the decoded data (which is typically a UTF-8 encoded string).

Syntax

    {{ input_string | base64_decode }}
Arguments

The base64_decode filter does not require any arguments.

Code Samples

Example 1: Decoding a Base64-Encoded String

    {% assign encoded_data = "SGVsbG8sIHdvcmxkIQ==" %}
    {{ encoded_data | base64_decode }}
Output:
Hello, world!
Example 2: Decoding an Image (Assuming Base64 Data)

    {% assign encoded_image_data = "iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==" %}
    <img src="data:image/png;base64,{{ encoded_image_data }}" alt="Decoded Image" />
Output: An image would be rendered in place of the above code.

Example 3: Decoding and Converting to a Number (e.g., Timestamp)

    {% assign encoded_timestamp = "MTU4MjU3NTQwMA==" %}
    {{ encoded_timestamp | base64_decode | to_number }}
Output:
1582575400

Outliers and Special Cases

  • Invalid Base64 Input: If the input string is not valid Base64, the filter might return an empty string or an error.
  • Non-String Input: If the input is not a string, the filter might attempt to convert it to a string or return an error.
  • Binary Data: While the filter returns a string, the decoded data could be binary in nature (e.g., an image). You might need to use additional mechanisms or tags to handle and display binary data appropriately.

Key Points

  • The base64_decode filter is crucial when working with Base64-encoded data within your templates.
  • Ensure the input string is valid Base64 to avoid errors.
  • Understand the nature of the decoded data (whether it's text or binary) and handle it accordingly.
  • The filter assumes the decoded data is in UTF-8 format. If it's not, you'll need additional conversion.
  • The decoded output is a string, even if the original data was not textual (like images or other binary files).