Skip to content

Conversation

@codefuturist
Copy link

Summary

Enable safe relative path imports (../, ../../) in Jinja2 templates, allowing templates to import macros from parent directories and centralized libraries.

Problem

Templates could only import macros from their immediate directory due to os.path.basename() stripping the directory path and Jinja2 blocking ../ for security.

Solution

  • Custom SafeRelativeLoader class that safely enables relative imports
  • Security boundary using os.path.commonpath() to prevent path traversal
  • Search order: template dir → cwd → common root
  • Full backward compatibility maintained

Changes

  • jinja2cli/cli.py: Add SafeRelativeLoader (~65 lines)
  • tests/test_jinja2cli.py: Add 2 tests for relative imports
  • tests/files/: Add test templates demonstrating nested imports

Testing

  • ✅ All 13 existing tests pass
  • ✅ 2 new tests for ../ and ../../../ imports
  • ✅ Verified symlink support
  • ✅ Security boundary enforcement tested

Example Usage

{# templates/pages/index.j2 #}
{% from "../../components/macros.j2" import widget %}
{% from "../shared/utils.j2" import helper %}

{{ widget("button") }}
{{ helper() }}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant