问题
I understand that Pug does not support dynamic includes or extends in templates. Ie
extend path/to/template
works but not
extend #{dynamic_path_to_template}
Is there a workaround (however convoluted) that will allow the same goal of modifying the template used by a view at runtime
Context: My use case is that I am developing an npm module and the template being used to extend other views is located inside the module. After the module is published and installed, the path will be defined (ie. node_modules/my_module/path/to/template) but during the development phase, I need to just be able to "npm link" to the module and have the templates work. I also would prefer not to hard code the links so I can publish the same code as tested.
回答1:
There is no way to do this for now, but you can work out your application architecture without dynamic extends.
Possible solution #1
Make a layout.jade that conditionally include multiple layouts:
layout.jade: if conditionalVariable include firstLayout.jade else include otherLayout
In your view, extend
layout.jade
, and defineconditionalVariable
in the controller (true
/false
):view.jade: extends layout block content p here goes my content!
Possible solution #2
Pass configurations to the layout
- var lang = req.getLocale(); doctype html block modifyLayout
split the project into multiple entrances, each entrance extends the layout and passes its different configs, and includes different things in different blocks
extends ../layout block modifyLayout - var lang = "en" //force language to be en in this page. block body include my-page-body
Possible solution #3
use something like terraform which uses pug as its rendering engine, but it enables you to use dynamic partials like this
!= partial(dynamicFileFromVariable)
来源:https://stackoverflow.com/questions/45824697/workaround-to-dynamic-includes-in-pug-jade