Skip to content

Commit

Permalink
[context] Improved flexibility of configuration variables
Browse files Browse the repository at this point in the history
Now the form {{var_name}} is allowed too.
  • Loading branch information
nemesifier committed Sep 8, 2016
1 parent dc9666b commit 1234c34
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 4 deletions.
3 changes: 1 addition & 2 deletions docs/source/general/basics.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down
5 changes: 3 additions & 2 deletions netjsonconfig/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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={}):
Expand All @@ -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


Expand Down
9 changes: 9 additions & 0 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.