Skip to content

Instantly share code, notes, and snippets.

@LeKovr
Created September 23, 2017 19:34
Show Gist options
  • Save LeKovr/2ee4f1ce941d44ea29864fdefcc3459a to your computer and use it in GitHub Desktop.
Save LeKovr/2ee4f1ce941d44ea29864fdefcc3459a to your computer and use it in GitHub Desktop.
Simple plpgsql template function with variables in json hash
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