Created
November 29, 2023 23:57
-
-
Save asimpletune/201619b803ba036cd2304beedceacd6f to your computer and use it in GitHub Desktop.
A macro in Tera (for Zola) to only permit a subset of markdown to become HTML
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{# | |
This macro is for removing desired html tags from markdown. You pass it literal text that is markdown, and it will remove the desired tags. There's an optional `allow_html` parameter that defaults to `false`. This controls whether to permit html that is mixed with markdown. | |
Note: you MUST store the result as a variable, before evaluating it as an expression, i.e. with the {{ }} syntax. | |
Otherwise, you will always get a string representation of the HTML. For some reason, saving the string, then evaluating | |
the expression doesn't have that issue. | |
TODO: file a bug. Case to reproduce is {{ filter_md(md, ["h1"]) }} does not work, but saving as a variable and then doing it does. | |
#} | |
{% macro filter_md(md, allow_html=false, disallow) %} | |
{% if not allow_html %} | |
{% set html_esc = md | striptags | markdown %} | |
{% else %} | |
{% set html_esc = md | markdown %} | |
{% endif %} | |
{% set_global result = html_esc %} | |
{% for tag in disallow %} | |
{% set_global result = self::strip_html(html_esc=result, tag=tag) %} | |
{% endfor %} | |
{% set_global result = result %} | |
{{ result }} | |
{% endmacro %} | |
{% macro strip_html(html_esc, tag) %} | |
{% set tokens = html_esc | split(pat="<" ~ tag) %} | |
{% set result = [] %} | |
{% for t in tokens | slice(start=1) %} | |
{% set t_2 = t | split(pat=">") | slice(start=1) | join(sep=">") %} | |
{% set_global result = result | concat(with=t_2) %} | |
{% endfor %} | |
{% set result = result | join(sep="") | split(pat="</" ~ tag ~ ">" ) | join(sep="" ) %} | |
{% set result = tokens[0] ~ result %} | |
{{ result }} | |
{% endmacro %} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment