Skip to content

Commit 1234c34

Browse files
committed
[context] Improved flexibility of configuration variables
Now the form {{var_name}} is allowed too.
1 parent dc9666b commit 1234c34

File tree

3 files changed

+13
-4
lines changed

3 files changed

+13
-4
lines changed

docs/source/general/basics.rst

+1-2
Original file line numberDiff line numberDiff line change
@@ -354,8 +354,7 @@ Let's see the result with:
354354
.. warning::
355355
**When using variables, keep in mind the following rules**:
356356

357-
* variables must be written in the form of ``{{ var_name }}``, including
358-
spaces around ``var_name``;
357+
* variables must be written in the form of ``{{ var_name }}`` or ``{{var_name}}``;
359358
* variable names can contain only alphanumeric characters and underscores;
360359
* unrecognized variables will be ignored;
361360

netjsonconfig/utils.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ def sorted_dict(dictionary):
3737
return OrderedDict(sorted(dictionary.items()))
3838

3939

40-
var_pattern = re.compile(r'\{\{\s(\w*)\s\}\}')
40+
var_pattern = re.compile(r'\{\{(.*)\}\}')
4141

4242

4343
def evaluate_vars(data, context={}):
@@ -58,8 +58,9 @@ def evaluate_vars(data, context={}):
5858
data[key] = evaluate_vars(value, context)
5959
elif isinstance(data, six.string_types):
6060
for var in var_pattern.findall(data):
61+
var = var.strip()
6162
if var in context:
62-
data = data.replace('{{ %s }}' % var, context[var])
63+
data = re.sub(var_pattern, context[var], data)
6364
return data
6465

6566

tests/test_utils.py

+9
Original file line numberDiff line numberDiff line change
@@ -133,3 +133,12 @@ def test_evaluate_vars_list(self):
133133
def test_evaluate_vars_list_in_dict(self):
134134
val = evaluate_vars({'l': ['{{ a }}', '{{ b }}']}, {'a': '1', 'b': '2'})
135135
self.assertEqual(val, {'l': ['1', '2']})
136+
137+
def test_evaluate_vars_nowhitespace(self):
138+
self.assertEqual(evaluate_vars('{{tz}}', {'tz': 'UTC'}), 'UTC')
139+
140+
def test_evaluate_vars_doublewhitespace(self):
141+
self.assertEqual(evaluate_vars('{{ tz }}', {'tz': 'UTC'}), 'UTC')
142+
143+
def test_evaluate_vars_strangewhitespace(self):
144+
self.assertEqual(evaluate_vars('{{ tz}}', {'tz': 'UTC'}), 'UTC')

0 commit comments

Comments
 (0)