用逗号分割对象,然后将其添加到hbs文件中

时间:2018-07-11 07:30:13

标签: javascript handlebars.js

我正在尝试动态添加带有自己的链接和标题的按钮。因此,从理论上讲,某个人可以在下面输入由逗号和标题组成的链接(分隔)(不是最佳解决方案,但这只是现在)。目前,该页面显示为带有1个按钮的按钮,其中包含2个链接和2个标题(如屏幕截图所示)

router.js

subList5 :: Num n => [n] -> n
sumList5 = sumTakeList 5

HBS

router.get('/products/:permalinkSlug', async (req, res, next) => {
  try {
    const permalinkJob = req.params.permalinkSlug
    const post = await postTools.getPostByPermalinkProducts(permalinkJob)
    post.authorName = (await postTools.getAuthorById(post.author_id)).real_name
    post.site_url = process.env.HOSTNAME


    post.poster = {
     "link": post.product_link.split(','),
      "title": post.link_title.split(',')
    }  

返回什么

{{#with poster}}
                  <a class="product_links_href" href="{{link}}" target="_blank">{{title}}</a>
              {{/with}}

enter image description here

1 个答案:

答案 0 :(得分:0)

您需要使用the each helper来遍历选项,但是对于您现在拥有的数组对象来说会有点尴尬。相反,您应该具有对象数组:

const SEPARATOR = /\s*,\s*/;

router.get('/products/:permalinkSlug', async (req, res, next) => {
  try {
    const permalinkJob = req.params.permalinkSlug;
    const post = await postTools.getPostByPermalinkProducts(permalinkJob);
    post.authorName = (await postTools.getAuthorById(post.author_id)).real_name
    post.site_url = process.env.HOSTNAME

    const links = post.product_link.split(SEPARATOR);
    const titles = post.link_title.split(SEPARATOR);

    const combined = links.map((link) => {
      return {
        link,
        title: titles.shift(),
      };
    });

    post.poster = combined;

然后您的模板可以遍历以下内容:

{{#each poster}}
    <a class="product_links_href" href="{{this.link}}" target="_blank">{{this.title}}</a>
{{/each}}