vladzam
vladzam

Reputation: 5908

Express.js + Handlebars - trying to use regex in view

I have the following handler when accessing /articles:

exports.articles = (function(req, res) {
    Article.find( function(err, articles){
        if(err) {
            res.send(500, { error: err });
        }

        res.render('articles', { articles: articles });
    });
});

And this is the corresponding view:

<section id="articles">
{{#each articles}}
    <article class="geometry">
        <h4>{{ title }}</h4>
        <hr>
        <p>{{ content }}</p>
        <!-- LINK TO ARTICLE HERE -->
    </article>
{{/each}}
</section>

I want to build that LINK so that whenever someone clicks it, the browser should navigate to /article/title-with-dashes-instead-of-spaces. Basically, I want to use title.replace(/\s/g, '-') on the title before appending it to the tag. Is there any way to format it like this on the view using handlebars? Or should it be done in the backend?

Thank you!

Upvotes: 2

Views: 959

Answers (1)

raina77ow
raina77ow

Reputation: 106453

I suppose it really belongs to the backend. And it's quite easy to do there:

Article.find( function(err, articles){
  if(err) {
    res.send(500, { error: err });
  }
  articles.forEach(function(article) {
    article.link = '/article/' + article.title.replace(/\s/g, '-');
  });
  res.render('articles', { articles: articles });
});

I'd rather have this code inserted into Article model as generateLink() method, as it simplifies its reusing.

An alternative is registering a Handlebars helper...

Handlebars.registerHelper('articleLink', function() {
  return '/article/' + this.title.replace(/\s/g, '-');
});

... then using it in the template:

<article class="geometry">
  <h4>{{ title }}</h4>
  <hr>
  <p>{{ content }}</p>
  <a href="{{ articleLink }}">Link</a>
</article>

Upvotes: 2

Related Questions