commit 46a9236: [Minor] Lua_util: Add jinja2 related functions

Vsevolod Stakhov vsevolod at highsecure.ru
Tue Mar 26 18:28:08 UTC 2019


Author: Vsevolod Stakhov
Date: 2019-03-26 17:32:34 +0000
URL: https://github.com/rspamd/rspamd/commit/46a9236766f51f44651a0615933e089a9efd1838

[Minor] Lua_util: Add jinja2 related functions

---
 .luacheckrc         |  1 +
 lualib/lua_util.lua | 49 +++++++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 50 insertions(+)

diff --git a/.luacheckrc b/.luacheckrc
index 7d5c6745e..77421fb59 100644
--- a/.luacheckrc
+++ b/.luacheckrc
@@ -22,6 +22,7 @@ globals = {
   'rspamd_gen_metatokens',
   'rspamd_parse_redis_server',
   'rspamd_paths',
+  'rspamd_env',
   'rspamd_plugins',
   'rspamd_redis_make_request',
   'rspamd_str_split',
diff --git a/lualib/lua_util.lua b/lualib/lua_util.lua
index 8d7f2bd69..0ae18a22e 100644
--- a/lualib/lua_util.lua
+++ b/lualib/lua_util.lua
@@ -113,6 +113,55 @@ exports.template = function(tmpl, keys)
   return lpeg.match(template_grammar, tmpl)
 end
 
+local function enrich_template_with_globals(env)
+  local newenv = exports.shallowcopy(env)
+  newenv.paths = rspamd_paths
+  newenv.env = rspamd_env
+
+  return newenv
+end
+--[[[
+-- @function lua_util.jinja_template(text, env[, skip_global_env])
+-- Replaces values in a text template according to jinja2 syntax
+-- @param {string} text text containing variables
+-- @param {table} replacements key/value pairs for replacements
+-- @param {boolean} skip_global_env don't export Rspamd superglobals
+-- @return {string} string containing replaced values
+-- @example
+-- lua_util.jinja_template("HELLO {{FOO}} {{BAR}}!", {['FOO'] = 'LUA', ['BAR'] = 'WORLD'})
+-- "HELLO LUA WORLD!"
+--]]
+exports.jinja_template = function(text, env, skip_global_env)
+  local lupa = require "lupa"
+
+  if not skip_global_env then
+    env = enrich_template_with_globals(env)
+  end
+
+  return lupa.expand(text, env)
+end
+
+--[[[
+-- @function lua_util.jinja_file(filename, env[, skip_global_env])
+-- Replaces values in a text template according to jinja2 syntax
+-- @param {string} filename name of file to expand
+-- @param {table} replacements key/value pairs for replacements
+-- @param {boolean} skip_global_env don't export Rspamd superglobals
+-- @return {string} string containing replaced values
+-- @example
+-- lua_util.jinja_template("HELLO {{FOO}} {{BAR}}!", {['FOO'] = 'LUA', ['BAR'] = 'WORLD'})
+-- "HELLO LUA WORLD!"
+--]]
+exports.jinja_template_file = function(filename, env, skip_global_env)
+  local lupa = require "lupa"
+
+  if not skip_global_env then
+    env = enrich_template_with_globals(env)
+  end
+
+  return lupa.expand_file(filename, env)
+end
+
 exports.remove_email_aliases = function(email_addr)
   local function check_gmail_user(addr)
     -- Remove all points


More information about the Commits mailing list