Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Templates in parent directories can't be referenced #9

Closed
chocolateboy opened this issue Sep 21, 2018 · 0 comments · Fixed by #11
Closed

Templates in parent directories can't be referenced #9

chocolateboy opened this issue Sep 21, 2018 · 0 comments · Fixed by #11
Labels

Comments

@chocolateboy
Copy link
Owner

chocolateboy commented Sep 21, 2018

parcel-plugin-nunjucks1.0.0
parcel1.9.7, 1.10.0-beta.1
nodev10.11.0
OS Linux (Arch)

(This is mentioned in #4 (and #7), but is broken out here as improving the documentation is a separate issue.)

Affected directives:

Currently the base template directory is set to the directory of each template asset e.g. if the template is located at src/html/screens/page-1.html.njk, the base template directory for the nunjucks environment associated with that file is src/html/screens. nunjucks doesn't allow templates to be loaded "outside the box" of the template directory, for security reasons, so referencing a template in a parent directory (e.g. ../macros/util.html.njk) ends up failing silently, by default (with or without Parcel) e.g.:

src/html/screens/page-1.html.njk

{% import "../macros/util.html.njk" as util %}

<h1>Welcome to Page 1!</h1>

test-default.js

const nunjucks = require('nunjucks')
const Path     = require('path')

const templatePath = Path.resolve('./src/html/screens/page-1.html.njk')
const templateDir = Path.dirname(templatePath)
const env = nunjucks.configure(templateDir)

try {
    const result = env.render(templatePath)
    console.log('result:', result)
} catch (err) {
    console.error('error:', err)
}

Output

result: null

Adding error reporting doesn't help as nunjucks doesn't flag the violation where it occurs, which leads to a cryptic error downstream complaining that a file that exists is not found:

test-error.js

const nunjucks = require('nunjucks')
const Path     = require('path')

const templatePath = Path.resolve('./src/html/screens/page-1.html.njk')
const templateDir = Path.dirname(templatePath)
const env = nunjucks.configure(templateDir)

function report (err, result) {
    if (err) {
        console.error('error:', err)
    } else {
        console.log('result:', result)
    }
}

try {
    env.render(templatePath, report)
} catch (err) {
    report(err)
}

Output

error: Template render error: (src/html/screens/page-1.html.njk)
Error: template not found: src/html/macros/util.html.njk

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant