Search code examples
javascriptformattingrivets.js

How to prefix values when templating them with rivets?


I am working with the rivets.js library to template data into my application. I am stuck at a kind of a formatting issue. How do I format values while templating them?

For example I have to template the user's photo location inside the image tag and I am getting the name of the file stored on the server from my DB.

It will be a hashed value but I need to prefix it with /img/uploads/ or something like that and postfix it with maybe .jpeg

I am checking if the value is null or not and this is my code:

<img rv-unless="user.photo" src="img/avatars/sunny-big.png" alt="me" data-toggle="modal" data-target="#myModal">
<img rv-if="user.photo" rv-src="user.photo" alt="me" data-toggle="modal" data-target="#myModal">
<i class="fa fa-camera"></i>

If I do something like rv-src="/img/uploads/user.photo", it wouldn't work for obvious reasons. How to get around this problem?


Solution

  • I think the solution to your problem is using formatters Rivets. They are like filters in AngularJS and support piping.

    You can define a formatter as follows:

    rivets.formatters.imgPath = function(value){
      return '/img/uploads/' + value + '.jpeg'
    }
    

    Then you can use it in your markup like:

    rv-src="user.photo | imgPath"