diff --git a/docs/template-files.md b/docs/template-files.md index f7185a2..c2b90ab 100644 --- a/docs/template-files.md +++ b/docs/template-files.md @@ -207,6 +207,17 @@ Resources: Runtime: "python3.7" ``` +### code_array + +Sometimes you might want to take the contents of a file as input for an array (line-by-line). Combine `code()` with `code_array` to make that happen: + +```yaml +Resources: + ... + ListOfItems: {{ code('my-list') | code_array }} +``` + + ### file diff --git a/formica/loader.py b/formica/loader.py index ca4b35d..a88923c 100644 --- a/formica/loader.py +++ b/formica/loader.py @@ -41,6 +41,9 @@ def code_escape(source): return source.replace("\n", "\\n").replace('"', '\\"') +def code_array(source): + lines = source.split("\\n") + return '[' + ','.join(['"%s"' % line for line in lines]) + ']' def mandatory(a): from jinja2.runtime import Undefined @@ -69,9 +72,13 @@ def __init__(self, path=".", filename="*", variables=None, main_account_paramete self.path = path self.filename = filename self.env = Environment(loader=FileSystemLoader("./", followlinks=True)) - self.env.filters.update( - {"code_escape": code_escape, "mandatory": mandatory, "resource": resource, "novalue": novalue} - ) + self.env.filters.update({ + "code_escape": code_escape, + "code_array": code_array, + "mandatory": mandatory, + "resource": resource, + "novalue": novalue, + }) self.variables = variables self.main_account_parameter = main_account_parameter diff --git a/tests/unit/test_loader.py b/tests/unit/test_loader.py index 10617e6..e69dc8a 100644 --- a/tests/unit/test_loader.py +++ b/tests/unit/test_loader.py @@ -333,6 +333,19 @@ def test_code_includes_and_escapes_code(load, tmpdir): assert actual == {"Description": "test\n\"something\""} +def test_code_with_code_array(load, tmpdir): + example = '{"Resources": {"Test": {{ code("test.py") | code_array }} }}' + pycode = "test\n\"something\"\nanother line" + with Path(tmpdir): + with open('test.template.json', 'w') as f: + f.write(example) + with open('test.py', 'w') as f: + f.write(pycode) + load.load() + actual = json.loads(load.template()) + assert actual == {"Resources": {"Test": ["test", "\"something\"", "another line"]}} + + def test_code_allows_to_include_files_from_parent(load, tmpdir): parent = '{"Resources": {"Test": {"From": "Moduledir"}}}' module = '{"Description": "{{ code("../test.txt") }}"}'