Pug/Jade 中动态包含的解决方法 [英] Workaround to dynamic includes in Pug/Jade

查看:65
本文介绍了Pug/Jade 中动态包含的解决方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解 Pug 不支持模板中的动态包含或扩展.即

I understand that Pug does not support dynamic includes or extends in templates. Ie

extend path/to/template 

有效但无效

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

上下文:我的用例是我正在开发一个 npm 模块,用于扩展其他视图的模板位于模块内部.发布并安装模块后,将定义路径(即 node_modules/my_module/path/to/template),但在开发阶段,我只需要能够npm 链接"到模块并拥有模板工作.我也不想对链接进行硬编码,这样我就可以发布与测试相同的代码.

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.

推荐答案

目前没有办法做到这一点,但您可以在没有动态扩展的情况下制定您的应用程序架构.

There is no way to do this for now, but you can work out your application architecture without dynamic extends.

  1. 制作一个有条件地包含多个布局的layout.jade:

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

layout.jade:

if conditionalVariable
    include firstLayout.jade
else
    include otherLayout

  • 在您看来,扩展layout.jade,并在控制器中定义conditionalVariable (true/false):

  • 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!
    

  • 可能的解决方案 #2

    1. 将配置传递给布局

    1. 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
    

  • 可能的解决方案 #3

    使用类似 terraform 之类的东西,它使用 pug 作为其渲染引擎,但它使您能够像这样使用动态部分

    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)
    

    这篇关于Pug/Jade 中动态包含的解决方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆