tests-always-included / mo

Mustache templates in pure bash
Other
563 stars 67 forks source link

Triple braces for HTML entity escaping #35

Closed sc0ttj closed 2 years ago

sc0ttj commented 5 years ago

Would it be possible to pass triple braced variables to an HTML entity decoding function, before being returned?

So that we can do this:

var="me & you"

echo "It's for {{$var}}" | mo        # double braces, gives "It's for me & you" 

echo "It's for {{{$var}}}" | mo    # triple braces, gives "It's for me & you" 

Here are some funcs that may be of interest, that I use like so:

echo "For me & you" | html_decode

function html_decode {
  read STDIN
  STDIN="${STDIN:-$@}"
  local LC_CTYPE=C
  [ "`which python3`" != "" ] && echo "${STDIN[@]}" |  python3 -c 'import html, sys; [print(html.escape(l), end="") for l in sys.stdin]' && return
  echo "${STDIN[@]}" | perl -MHTML::Entities -pe 'decode_entities($_);'
}

function html_encode {
  read STDIN
  STDIN="${STDIN:-$@}"
  local LC_CTYPE=C
  [ "`which python3`" != "" ] && echo "${STDIN[@]}" | python3 -c 'import html, sys; [print(html.unescape(l), end="") for l in sys.stdin]' && return
  echo "${STDIN[@]}" | perl -MHTML::Entities -pe 'encode_entities($_);'
}

Of course, I am happy for these funcs to continue to live outside of the mo script, but still need to make mo decode stuff inside triple braces automatically.. or at least to recognise triple braced vars as a "different thing", which needs an extra step in parsing the output..

Any ideas please?

Thanks :)

fidian commented 2 years ago

If you define the functions in shell code, you are already able to do this. Let's presume your html_decode function exists.

# You must add mo to the environment
. mo
# Add your function to the environment
. html_decode.sh
echo "It's for {{html_decode var}}" | mo

The html_decode function would look like this

html_decode() {
    local varName=$1
    local content="${!varName}"
    local LC_CTYPE=C
    [ "`which python3`" != "" ] && echo "$content" |  python3 -c 'import html, sys; [print(html.escape(l), end="") for l in sys.stdin]' && return
    echo "$content" | perl -MHTML::Entities -pe 'decode_entities($_);'
}

Sorry for taking so long to reply. If this doesn't suit your needs, let me know about it in a different issue.