如何在ejs模板的内容中设置字符限制 [英] How to set character limits in content in ejs template
问题描述
我正在从EJS模板的Mognodb中获取内容.我的说明字段包含超过500个字符,但我想在视图中仅显示50个字符.
I am fetching content from Mognodb in EJS template. I have description field which contains more then 500 characters, but I want to show only 50 Characters in my view.
谁能告诉我该怎么做.
推荐答案
In the view you can use JavaScript String.prototype.substring():
<%= description.substring(0, 50) %>
在MongoDB中,您可以使用 $ substr 返回新的所需的50个字符的字段:
Within MongoDB you can use $substr to return a new field with the desired 50 characters:
db.collectionName.aggregate([{
$project: {
title: 1,
shortDescription: {
$substr: ["$description", 0, 50]
}
}
}]);
请注意,在代码示例中,我正在使用名为 collectionName
的集合以及诸如 title
和 description
之类的字段名称.仅返回 title
和 shortDescription
,并且最多只能在视图中使用50个字符
Note that in the code example I am using a collection named collectionName
and fields names like title
and description
.. This way will be returned only title
and shortDescription
with a limit to 50 characters to use in the view
这篇关于如何在ejs模板的内容中设置字符限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!