javascript 仅使用 Mustache 显示列表中的第一项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11147373/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 12:11:48  来源:igfitidea点击:

only show the first item in list using Mustache

javascriptmustache

提问by Alex

I am using the mustache template engine and I only want to display the first item in a long list but cant seem to find the docs for doing so?

我正在使用 mustache 模板引擎,我只想显示长列表中的第一项,但似乎找不到这样做的文档?

if I use:

如果我使用:

{{# links}}<a href="{{& url}}">{{& title }}</a>{{/ links}}

i get all of the links, however i only want the first one to be displayed, sounds easy but I cant find any docs on this.

我获得了所有链接,但是我只想显示第一个链接,听起来很简单,但我找不到任何有关此的文档。

回答by Millad

This solution is working with the new version of Mustache.js (only):

此解决方案适用于新版本的 Mustache.js(仅适用于):

mustache.render("{{a.0}}", {a: ['hi','world']})
=> 'hi'

回答by arc

The solution @Millad presented almost worked for me. Using handlebars.js though I had to use it with brackets.

@Millad 提出的解决方案几乎对我有用。使用 handlebars.js 虽然我不得不用括号来使用它。

{{ a.[0] }}

=> hello

=> 你好

res.render('view', { a: ['hello', 'world'] })

回答by artlung

Mustache has does not have logic, from the docs:

Mustache has 没有逻辑,来自文档

We call it "logic-less" because there are no if statements, else clauses, or for loops. Instead there are only tags. Some tags are replaced with a value, some nothing, and others a series of values. This document explains the different types of Mustache tags.

我们称其为“无逻辑”,因为没有 if 语句、else 子句或 for 循环。相反,只有标签。一些标签替换为一个值,一些什么都没有,而另一些则替换为一系列值。本文档解释了不同类型的 Mustache 标签。

So what you essentially want is a mechanism to do an if link is the first- so you can handle this on the data side, by only putting 1 element in your data, or by adding a chunk of data like when you're putting your data in you add a value like displayand set it to 'inline' or 'none' then in your template do:

所以你本质上想要的是一种机制if link is the first- 所以你可以在数据方面处理这个问题,只在你的数据中放入 1 个元素,或者通过添加一大块数据,比如当你将数据放入时添加一个value likedisplay并将其设置为“inline”或“none”,然后在您的模板中执行以下操作:

{{# links}}<a href="{{& url}}" style="display: {{display}};">{{& title }}</a>{{/ links}}

Then, later, you can call scripting in page to change the style.displayon some user or application action.

然后,稍后,您可以在页面中调用脚本来更改style.display某些用户或应用程序的操作。

Those are my first though it may simply be easier to set data = data[0]for this particular template. The problem is you probably WANT to use that whole list at some point, to comment on that I'd need to see more your usage and where the data's populating from.

这些是我的第一个,尽管data = data[0]为这个特定模板设置可能更容易。问题是您可能想在某个时候使用整个列表,以评论我需要查看更多您的使用情况以及数据从何处填充。