brettviren / moo

ruminants on module oriented programming
GNU General Public License v3.0
4 stars 4 forks source link

template paths not propagated to template includes #29

Closed alessandrothea closed 3 years ago

alessandrothea commented 3 years ago

Hi @brettviren ,

While playing with custom templates earlier today I stumbled on an issue when trying to include a macro file in a jinja template.

I have 2 jinja files, a template (OpMonStructs.hpp.j2) and a macro file (opmon_hpp_macros.j2)

schema/
└── opmonlib
    ├── opmon_hpp_macros.j2
    └── OpMonStructs.hpp.j2

OpMonStructs.hpp.j2 includes opmon_hpp_macros.j2 as a jinjia import:

{% import 'opmonlib/opmon_hpp_macros.j2' as opmcppm %}

but Jinja fails to resolve opmonlib/opmon_hpp_macros.j2 even if schema is in the moo template path. After a quick look into the code I think the issue might be that moo.utils.imports doesn't pass the template paths to the resolve function. After patching my local copy as follows

def imports(template, tpath=None):
    'Return all files imported by template'
    # env = env_from_tmplfile(template, tpath)
    # ...
    path = make_path(template, tpath)
    style_params = get_style(template)
    env = make_env(path, **style_params)
    ast = env.parse(open(template, 'rb').read().decode())
    subs = meta.find_referenced_templates(ast)
-    ret = [resolve(one) for one in subs]
+    ret = [resolve(one, tpath) for one in subs]
    return ret

the issues of jinjia not finding opmonlib/opmon_hpp_macros.j2 seem gone and the template is correctly instantiated. Would you mind having a look? Thanks!

Alessandro

brettviren commented 3 years ago

Thanks for this, @alessandrothea ! I reproduce this with moo imports.

The problem is due to me mistakenly thinking Jinja returned an already resolved path from find_referenced_templates().

I'll commit a fix next. Instead of asking moo to resolve(), it relies on Jinja to do the resolution. In this way we can assure the import would also be resolved when later used in a render.

A few other bug fixes have piled up so I'll make a new release to include them and this fix.

alessandrothea commented 3 years ago

Awesome, thanks!

Just to give you the heads up, I will probably ask for a new tag, once you're happy with the fix! ;-)

brettviren commented 3 years ago

As promised :)

https://github.com/brettviren/moo/releases/tag/0.5.7

alessandrothea commented 3 years ago

Thanks!