Created
September 23, 2017 19:34
-
-
Save LeKovr/2ee4f1ce941d44ea29864fdefcc3459a to your computer and use it in GitHub Desktop.
Simple plpgsql template function with variables in json hash
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
CREATE OR REPLACE FUNCTION template(tmpl TEXT, vars JSONB) RETURNS TEXT IMMUTABLE LANGUAGE 'plpgsql' AS | |
$_$ | |
DECLARE | |
r RECORD; | |
BEGIN | |
FOR r IN SELECT * from jsonb_each_text(vars) LOOP | |
tmpl := regexp_replace(tmpl,'{{\s*' || r.key || '\s*}}', r.value); | |
END LOOP; | |
RETURN tmpl; | |
END; | |
$_$; | |
/* | |
db-> SELECT template('{{ name}}, you win {{win}}!', '{"name":"John", "win":12345}'); | |
template | |
---------------------- | |
John, you win 12345! | |
*/ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment