Skip to content

Commit

Permalink
Fix template loading
Browse files Browse the repository at this point in the history
Signed-off-by: NilashishC <[email protected]>
  • Loading branch information
NilashishC committed Jul 26, 2023
1 parent 0c3d1f1 commit 003e8f3
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 8 deletions.
4 changes: 2 additions & 2 deletions src/ansible_creator/actions/init.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,14 +67,14 @@ def run(self):
Path(file_path).touch()

# render and write collection skel templates
data = dict(
init_data = dict(
namespace=self._namespace,
collection_name=self._collection_name,
)

for template in COLLECTION_SKEL_TEMPLATES:
rendered_content = self._templar.render(
template_name=template, contents=data
template_name=template, data=init_data
)
dest_file = os.path.join(col_path, template.split(".j2")[0])
with open(dest_file, "w") as df:
Expand Down
1 change: 0 additions & 1 deletion src/ansible_creator/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import argparse
from .actions.init import AnsibleCreatorInit
from .actions.create import AnsibleCreatorCreate
from .constants import MessageColors


class AnsibleCreatorCLI:
Expand Down
20 changes: 15 additions & 5 deletions src/ansible_creator/template_engine/__init__.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
try:
from jinja2 import Environment, StrictUndefined, PackageLoader
from jinja2 import Environment, StrictUndefined

HAS_JINJA2 = True
except ImportError:
HAS_JINJA2 = False
from importlib import resources


class Templar:
Expand All @@ -16,10 +17,19 @@ def __init__(self):
self.env = Environment(
undefined=StrictUndefined,
keep_trailing_newline=True,
loader=PackageLoader("ansible_creator", "templates"),
)

def render(self, template_name, contents):
template = self.env.get_template(template_name)
rendered_content = template.render(contents)
def render(self, template_name, data):
template_content = self.get_template_content(template_name)
rendered_content = self.env.from_string(template_content).render(data)
return rendered_content

def get_template_content(self, template_name):
package = "ansible_creator.templates"

with resources.files(package).joinpath(template_name).open(
"r", encoding="utf-8"
) as fh:
content = fh.read()

return content

0 comments on commit 003e8f3

Please sign in to comment.