Search code examples
javascriptexpress-handlebars

How to change font color negative number , positive number data from json with handlebars?


I have get json data from external api.

<h4>ChangePercent <span class="badge bg-secondary"> {{ stock.changePercent}} % </span></h4>

Code above is get response data json and it's return with number type, and use template engine with express handlebars to render. It's work , But.. I want to change font color red if stock.changePercent < 0 , green for stock.changePercent > 0


Solution

  • You can conditionally render in handlebarsjs

    Template:

    <h4>ChangePercent <span class="badge bg-secondary" {{#if stockChangeSmallerThanZero}}style="color: red;"{{/if}}>  {{ stock.changePercent}} %    </span></h4> 
    

    Variable

    {
      stockChangeSmallerThanZero: true,
    }
    

    Online playground: https://handlebarsjs.com/playground.html#format=1&currentExample=%7B%22template%22%3A%22%3Ch4%3EChangePercent%20%3Cspan%20class%3D%5C%22badge%20bg-secondary%5C%22%20%7B%7B%23if%20stockChangeSmallerThanZero%7D%7Dstyle%3D%5C%22color%3A%20red%3B%5C%22%7B%7B%2Fif%7D%7D%3E%20%20%7B%7B%20stock.changePercent%7D%7D%20%25%20%20%20%20%3C%2Fspan%3E%3C%2Fh4%3E%20%22%2C%22partials%22%3A%5B%5D%2C%22input%22%3A%22%7B%5Cn%20%20stockChangeSmallerThanZero%3A%20true%2C%5Cn%7D%5Cn%22%2C%22output%22%3A%22%3Ch4%3EChangePercent%20%3Cspan%20class%3D%5C%22badge%20bg-secondary%5C%22%20style%3D%5C%22color%3A%20red%3B%5C%22%3E%20%20%20%25%20%20%20%20%3C%2Fspan%3E%3C%2Fh4%3E%20%22%2C%22preparationScript%22%3A%22%22%2C%22handlebarsVersion%22%3A%224.7.7%22%7D