我想从富文本中截断文本,如下所示。我尝试了很多东西,但没有奏效。
{% for piece in data.pieces %}
<div class="col-md-4 col-sm-6">
<div class="single-product mb-55 animated fadeInUp" data-animate="fadeInUp" data-delay=".1" style="animation-duration: 0.6s; animation-delay: 0.1s;">
<span class="tip">{{ piece.title }}</span>
<img src="img/products/[email protected]" data-rjs="2" alt="" data-rjs-processed="true" width="237" height="193">
<h3 class="h5">
{{ apos.area(piece, 'body') }}
</h3>
</div>
</div>
<!-- End of Single Product -->
{% endfor %}
我需要截断这部分。不知道有没有其他的方式来显示描述:
{{ apos.area(piece, 'body') }}
有许多不同的方法可以解决这个问题,您在要求方面没有提供太多,因此需要对这些进行优化以满足您的需求。
注意:
truncate
对富文本(标记)使用 Nunjuck 的过滤器将在代码中包含所有 HTML 标记和空格,而不是截断限制。下面的示例使用 Nunjuck 的截断。这可能会导致标记中的标记损坏,如果一个标记被打开,达到限制,然后永远不会关闭。我建议将truncate-html 之类的东西实现为项目级 Nunjucks 助手。请参阅在 Apostrophe 中实现自定义 Nunjucks 助手
在您作品的模式中,在定义body
区域时,在您的apostrophe-rich-text
选项中添加一些标志
{
name: 'body',
label: 'Body',
type: 'area',
options: {
widgets: {
'apostrophe-rich-text': {
toolbar:[...], // toolbar settings
styles:[...], // styles settings
truncate: 250 // truncates after 250 characters
}
}
}
}
然后,在apostrophe-rich-text-widgets
模板的项目级别覆盖上,注意要传递给富文本小部件的那些设置。使用 Nunjucks 内置truncate
过滤器来更改小部件中的文本内容。
在 lib/modules/apostrophe-rich-text-widgets/views/widget.html
<div data-rich-text class="apos-rich-text">
{% if data.options.truncate %}
{{ data.widget.content | safe | truncate(data.options.truncate) }}
{% else %}
{{ data.widget.content | safe }}
{% endif %}
</div>
优点:这将适用于您在上面提供的设置,而不会改变您当前的body
.
缺点:这种方法是蛮力的。您在区域级别指定此选项,因此该区域内的所有富文本小部件都将收到这些选项,并且它们都将被相应地截断。如果您使用单例来保存您的描述,同样的方法会更有效,因为您可以严格控制截断选项发生的位置。
此方法涉及创建一个新的小部件,其中包含一个富文本单例和用于控制是否截断文本以及截断文本数量的选项。我要调用小部件truncate-rich-text
在lib/modules/truncate-rich-text-widgets/index.js
(创建此文件和路径)
module.exports = {
extend: 'apostrophe-widgets',
label: 'Truncate Rich Text',
addFields: [
{
name: 'content',
label: 'Content',
type: 'singleton',
widgetType: 'apostrophe-rich-text',
options: {
toolbar:[],
styles:[]
}
},
{
name: 'truncate',
label: 'Truncate this text?',
type: 'boolean',
choices: [
{ label: 'Yes', value: true, showFields: ['truncateCharacters'] },
{ label: 'No', value: false }
]
},
{
name: 'truncateCharacters',
label: 'Character limit',
type: 'integer'
}
]
};
然后在lib/modules/truncate-rich-text-widgets/views/widget.html
(创建这个)
<div class="truncate-rich-text">
{% if data.widget.truncate %}
{{ data.widget.content.items[0].content | safe | truncate(data.widget.truncateCharacters) }}
{% else %}
{{ data.widget.content.items[0].content | safe }}
{% endif %}
</div>
最后,将此新模块添加到您的app.js
配置中。
var path = require('path');
var apos = require('apostrophe')({
shortName: 'myProject',
modules: {
// ... other modules
'truncate-rich-text-widgets': {},
}
});
优点:这提供了对哪些文本小部件被截断的更细粒度的控制,并且可以在您的站点中更广泛地使用。
缺点:这将是您站点配置中的一个新小部件,这意味着您必须迁移您的内容才能使用它。这也从编辑器用户体验中消除了在 Apostrophe 中编辑文本的大量上下文,这是一个无赖。
就像我说的,有多种方法可以实现这一点,并且在不同情况下也有 UX 微妙之处(也许您只向已注销的用户显示截断的文本,而将完整内容留给编辑器,因为这会使您的文本混淆保存时继续消失)。希望这将为您找到正确的实现开辟一些途径。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句