From c61c78447b855c3fef1def5ce962156d2ce2e7f3 Mon Sep 17 00:00:00 2001 From: Kim Alvefur Date: Sat, 9 Dec 2023 14:57:41 +0100 Subject: util.xtemplate: Adopt {-path-} syntax to strip preceding and/or trailing whitespace Seen in some other template languages --- teal-src/prosody/util/xtemplate.tl | 16 ++++++++++++---- util/xtemplate.lua | 16 ++++++++++++---- 2 files changed, 24 insertions(+), 8 deletions(-) diff --git a/teal-src/prosody/util/xtemplate.tl b/teal-src/prosody/util/xtemplate.tl index 7f3b513a..9b6b678b 100644 --- a/teal-src/prosody/util/xtemplate.tl +++ b/teal-src/prosody/util/xtemplate.tl @@ -23,8 +23,16 @@ local type filter_coll = { string : filter_t } local function render(template : string, root : st.stanza_t, escape : escape_t, filters : filter_coll) : string escape = escape or st.xml_escape; - return (s_gsub(template, "%b{}", function(block : string) : string + return (s_gsub(template, "(%s*)(%b{})(%s*)", function(pre_blank : string, block : string, post_blank : string) : string local inner = s_sub(block, 2, -2); + if inner:sub(1, 1) == "-" then + pre_blank = ""; + inner = inner:sub(2); + end + if inner:sub(-1, -1) == "-" then + post_blank = ""; + inner = inner:sub(1, -2); + end local path, pipe, pos = s_match(inner, "^([^|]+)(|?)()"); if not path is string then return end local value : string | st.stanza_t @@ -87,14 +95,14 @@ local function render(template : string, root : st.stanza_t, escape : escape_t, if value is string then if not is_escaped then value = escape(value); end - return value; + return pre_blank .. value .. post_blank; elseif st.is_stanza(value) then value = value:get_text(); if value then - return escape(value); + return pre_blank .. escape(value) .. post_blank; end end - return ""; + return pre_blank .. post_blank; end)); end diff --git a/util/xtemplate.lua b/util/xtemplate.lua index 1c58c63e..56413012 100644 --- a/util/xtemplate.lua +++ b/util/xtemplate.lua @@ -8,8 +8,16 @@ local st = require("prosody.util.stanza"); local function render(template, root, escape, filters) escape = escape or st.xml_escape; - return (s_gsub(template, "%b{}", function(block) + return (s_gsub(template, "(%s*)(%b{})(%s*)", function(pre_blank, block, post_blank) local inner = s_sub(block, 2, -2); + if inner:sub(1, 1) == "-" then + pre_blank = ""; + inner = inner:sub(2); + end + if inner:sub(-1, -1) == "-" then + post_blank = ""; + inner = inner:sub(1, -2); + end local path, pipe, pos = s_match(inner, "^([^|]+)(|?)()"); if not (type(path) == "string") then return end local value @@ -74,12 +82,12 @@ local function render(template, root, escape, filters) if type(value) == "string" then if not is_escaped then value = escape(value); end - return value + return pre_blank .. value .. post_blank elseif st.is_stanza(value) then value = value:get_text(); - if value then return escape(value) end + if value then return pre_blank .. escape(value) .. post_blank end end - return "" + return pre_blank .. post_blank end)) end -- cgit v1.2.3