Skip to content

Commit

Permalink
✨ Dynamically import modules of extensions
Browse files Browse the repository at this point in the history
Related to moremoban#90
  • Loading branch information
ayan-b committed Feb 18, 2019
1 parent 26ac367 commit 4b8170d
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 2 deletions.
12 changes: 12 additions & 0 deletions moban/jinja2/engine.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from importlib import import_module

from jinja2 import Template, Environment, FileSystemLoader
from lml.loader import scan_plugins_regex
from lml.plugin import PluginInfo, PluginManager
Expand Down Expand Up @@ -74,6 +76,7 @@ def __init__(self, template_dirs, extensions=None):
if is_extension_list_valid(extensions):
# because it is modified here
env_params["extensions"] += extensions
import_module_of_extension(extensions)
self.jj2_environment = Environment(**env_params)
for filter_name, filter_function in FILTERS.get_all():
self.jj2_environment.filters[filter_name] = filter_function
Expand Down Expand Up @@ -136,3 +139,12 @@ def is_extension_list_valid(extensions):
and isinstance(extensions, list)
and len(extensions) > 0
)


def import_module_of_extension(extensions):
modules = set()
if extensions:
for extension in extensions:
modules.add(extension.split('.')[0])
for module in modules:
globals()[module] = import_module(module)
2 changes: 1 addition & 1 deletion tests/requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,4 @@ black;python_version>="3.6"
isort;python_version>="3.6"
moban-handlebars
pypi-mobans-pkg

jinja2_time
19 changes: 18 additions & 1 deletion tests/test_engine.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import sys
import os

from mock import patch
Expand All @@ -6,7 +7,11 @@

import moban.exceptions as exceptions
from moban.plugins import ENGINES
from moban.jinja2.engine import Engine, is_extension_list_valid
from moban.jinja2.engine import (
Engine,
is_extension_list_valid,
import_module_of_extension,
)
from moban.plugins.context import Context
from moban.plugins.template import TemplateEngine, expand_template_directories

Expand Down Expand Up @@ -137,3 +142,15 @@ def test_extensions_validator():
actual.append(is_extension_list_valid(fixture))

eq_(expected, actual)


def test_import():
extensions = [
"jinja2.ext.do",
"jinja2_time.TimeExtension",
"jinja2.ext.loopcontrols",
]
import_module_of_extension(extensions)
modules = ["jinja2", "jinja2_time"]
for module in modules:
assert module in sys.modules

0 comments on commit 4b8170d

Please sign in to comment.