Workaround to dynamic includes in Pug/Jade

别等时光非礼了梦想. 提交于 2019-12-11 04:26:49

问题


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

  1. Make a layout.jade that conditionally include multiple layouts:

    layout.jade:
    
    if conditionalVariable
        include firstLayout.jade
    else
        include otherLayout
    
  2. In your view, extend layout.jade, and define conditionalVariable in the controller (true/false):

    view.jade:
    
    extends layout
    
    block content
        p here goes my content!
    

Possible solution #2

  1. Pass configurations to the layout

    - var lang = req.getLocale();
    doctype html
       block modifyLayout
    
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!