Skip to content

Instantly share code, notes, and snippets.

@xpe
Last active May 9, 2024 15:39
Show Gist options
  • Save xpe/ffd7f293421b14e7dc65545816045456 to your computer and use it in GitHub Desktop.
Save xpe/ffd7f293421b14e7dc65545816045456 to your computer and use it in GitHub Desktop.
Macro for Google Fonts links for use Tera (a templating engine written in Rust)
{% macro google_fonts(families) %}
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
{% set prefix = "https://fonts.googleapis.com/css2?" -%}
{% set s = "" -%}
{% for family in families -%}
{% if loop.index0 > 0 -%}
{% set_global s = s ~ "&" -%}
{% endif -%}
{% set_global s = s ~ "family=" ~ family -%}
{% endfor -%}
{% set href = prefix ~ s ~ "&display=swap" -%}
<link href="{{ href | safe }}" rel="stylesheet">
{% endmacro input %}

Gotchas

Here are some gotchmes and hopefully not gotchyous:

  • Don't write loop.index > 0 as it will always be true; loop.index is 1-indexed. Above, I needed the 0-indexed version: loop.index0. 1

  • "If you want to assign a value in the global context while in a for loop, you must use set_global" 2

  • Don't forget to use | safe with trusted strings. 3

  • Underscores are ok in Tera macro names but hyphens are not. 4

Footnotes

  1. Explained in https://keats.github.io/tera/docs/#for.

  2. Quoted from https://keats.github.io/tera/docs/#assignments except I changed the phrase "can use" to "must".

  3. From https://keats.github.io/tera/docs/#safe "Marks a variable as safe: HTML will not be escaped anymore. safe only works if it is the last filter of the expression"

  4. From https://github.com/Keats/tera/issues/913, valid characters are: a-zA-Z_0-9 but cannot start with 0-9

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment