I'm using handlebars with node.js and express and I have a custom registered helper for temperature display that I'd like to have access to a query parameter from the page URL.
The concept behind the helper is to handle Fahrenheit to Celsius conversion automatically based on whether ?tempFormat=F
or tempFormat=C
is in the URL or not. Here's the pseudo code for the custom helper I'd like to have:
hbs.registerHelper("formatTemp", function(temp) {
if (query parameter says to use Fahrenheit) {
temp = toFahrenheitStr(temp);
}
return temp;
});
So, I'd like my template to look like this:
{{#each temperatures}}
<div class="row {{{stripes @index}}}">
<div class="time">{{prettifyDate t}}</div>
<div class="atticTemp">{{formatTemp atticTemp}}</div>
<div class="outsideTemp">{{formatTemp outsideTemp}}</div>
<div class="spacer"></div>
</div>
{{/each}}
I'm working around the issue now by pulling request.query.tempFormat
and putting it in the data given to the template rendering:
app.get('/debug', function(request, response) {
var tempData = {
temperatures: data.temperatures,
units: request.query.tempFormat || "C"
};
response.render('debug', tempData);
});
And, then passing that data in the template:
{{#each temperatures}}
<div class="row {{{stripes @index}}}">
<div class="time">{{prettifyDate t}}</div>
<div class="atticTemp">{{formatTemp atticTemp ../units}}</div>
<div class="outsideTemp">{{formatTemp outsideTemp ../units}}</div>
<div class="spacer"></div>
</div>
{{/each}}
But, this seems messy because I have to pass the temperature units to every template render call and I have to then put them in every template where I want them used by a temperature display. They're sitting there in the request object already. So, I'm trying to figure out how to get access to the request object from a handlebars custom helper function? That way, I could save code for every render and save code in each template and have the tempFormat
query parameter just automatically apply to any use of formatTemp
in my templates.
Does anyone know how to get access to the request object from a handlebars custom helper without using a global?
location.pathname.indexOf('tempFormat=F')
– raidendevlocation.search
, notlocation.pathname
if it was a browser and I'm trying to avoid using globals so multiple requests don't have issues. – jfriend00