Permalink
Browse files

[context] Improved flexibility of configuration variables

Now the form {{var_name}} is allowed too.
  • Loading branch information...
nemesisdesign committed Sep 8, 2016
1 parent dc9666b commit 1234c34015d8c747f8ff07c05dbf4412e242461d
Showing with 13 additions and 4 deletions.
  1. +1 −2 docs/source/general/basics.rst
  2. +3 −2 netjsonconfig/utils.py
  3. +9 −0 tests/test_utils.py
@@ -354,8 +354,7 @@ Let's see the result with:
.. warning::
**When using variables, keep in mind the following rules**:
* variables must be written in the form of ``{{ var_name }}``, including
spaces around ``var_name``;
* variables must be written in the form of ``{{ var_name }}`` or ``{{var_name}}``;
* variable names can contain only alphanumeric characters and underscores;
* unrecognized variables will be ignored;
@@ -37,7 +37,7 @@ def sorted_dict(dictionary):
return OrderedDict(sorted(dictionary.items()))
var_pattern = re.compile(r'\{\{\s(\w*)\s\}\}')
var_pattern = re.compile(r'\{\{(.*)\}\}')
def evaluate_vars(data, context={}):
@@ -58,8 +58,9 @@ def evaluate_vars(data, context={}):
data[key] = evaluate_vars(value, context)
elif isinstance(data, six.string_types):
for var in var_pattern.findall(data):
var = var.strip()
if var in context:
data = data.replace('{{ %s }}' % var, context[var])
data = re.sub(var_pattern, context[var], data)
return data
@@ -133,3 +133,12 @@ def test_evaluate_vars_list(self):
def test_evaluate_vars_list_in_dict(self):
val = evaluate_vars({'l': ['{{ a }}', '{{ b }}']}, {'a': '1', 'b': '2'})
self.assertEqual(val, {'l': ['1', '2']})
def test_evaluate_vars_nowhitespace(self):
self.assertEqual(evaluate_vars('{{tz}}', {'tz': 'UTC'}), 'UTC')
def test_evaluate_vars_doublewhitespace(self):
self.assertEqual(evaluate_vars('{{ tz }}', {'tz': 'UTC'}), 'UTC')
def test_evaluate_vars_strangewhitespace(self):
self.assertEqual(evaluate_vars('{{ tz}}', {'tz': 'UTC'}), 'UTC')

0 comments on commit 1234c34

Please sign in to comment.