Changeset

13394:6debd8dd12ab

util.xtemplate: Adopt {-path-} syntax to strip preceding and/or trailing whitespace Seen in some other template languages
author Kim Alvefur <zash@zash.se>
date Sat, 09 Dec 2023 14:57:41 +0100
parents 13393:f72ca74de456
children 13395:1675d4b6363a
files teal-src/prosody/util/xtemplate.tl util/xtemplate.lua
diffstat 2 files changed, 24 insertions(+), 8 deletions(-) [+]
line wrap: on
line diff
--- a/teal-src/prosody/util/xtemplate.tl	Wed Dec 06 23:52:45 2023 +0100
+++ b/teal-src/prosody/util/xtemplate.tl	Sat Dec 09 14:57:41 2023 +0100
@@ -23,8 +23,16 @@
 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 @@
 
 		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
 
--- a/util/xtemplate.lua	Wed Dec 06 23:52:45 2023 +0100
+++ b/util/xtemplate.lua	Sat Dec 09 14:57:41 2023 +0100
@@ -8,8 +8,16 @@
 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 @@
 
 		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