简体   繁体   English

如何使用 EJS 和 110 进行组件组合(包含在包含中)?

[英]How to do component composition (includes within includes) with EJS and eleventy?

I'm using Eleventy , a static site generator to build a website.我正在使用Eleventy ,一个静态站点生成器来构建一个网站。 It supports a lot of templating languages, but EJS looks to be the best in that it's "just JavaScript", except, I cannot figure out how to do component composition, or whether it's at all possible.它支持很多模板语言,但EJS看起来是最好的,因为它“只是 JavaScript”,除了我不知道如何进行组件组合,或者它是否可能。 The EJS docs are, let's say, severely lacking.可以说,EJS 文档严重缺乏。

What I want to achieve is similar to what you'd do in React or Vue with props.children or <slot> , where you compose components, but it would obviously be done with partials here.我想要实现的目标类似于您在 React 或 Vue 中使用props.children<slot> ,您可以在其中组合组件,但在这里显然可以使用部分来完成。

For example, say I had a grid-item partial that accepted sizes it could render at, its tag name and "children", something like:例如,假设我有一个网格项目部分,它接受它可以呈现的大小、标签名称和“子项”,例如:

<%- include('../grid-item', {
  size: '50',
  tag: 'li',
  children: ANOTHER-INCLUDE,
}); %>

However, even the above example is a bit limiting, so what I'd really like to achieve is something like:然而,即使是上面的例子也有点限制,所以我真正想要实现的是:

<%- include('../grid', {
  tag: 'ul',
}, () => { %>
  <%- include('../grid-item', {
    size: '50',
    tag: 'li',
  }, () => { %>
    <div>ANY MARKUP</div>
  <% }); %>
<% }); %>

Is this possible?这可能吗? Am I approaching this from the wrong angle?我是从错误的角度接近这个吗?

Eleventy supports a workaround for this with Paired Shortcodes for Nunjucks and Liquid, but both of those templating languages seem severely limited, such as you can't even create an object of data. Eleventy 支持使用 Nunjucks 和 Liquid 的配对短代码解决此问题,但这两种模板语言似乎都受到严重限制,例如您甚至无法创建数据对象。

You can use Javascript Template Functions for this.您可以为此使用Javascript Template Functions

I have set up a components.js file that gets imported in my .eleventy.js config file.我已经设置了一个components.js文件,该文件被导入到我的.eleventy.js配置文件中。 That components file gets passed the eleventyConfig object, and then defines components like:该组件文件传递给了eleventyConfig对象,然后定义了如下组件:

eleventyConfig.addJavaScriptFunction("componentName", function(props) { … });

Then you can use that function in your js templates, by accessing it via this :然后你可以使用该功能在你的js模板,通过通过访问它this

module.exports = function(data) {
  return `
    <div>
      ${this.componentName(props)}
    </div>
  `;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM