Friday, December 9, 2016

freemarker template: safely pass optional freemarker boolean into javascript

New job! I started with CarGurus just this week. Great site if you want to both find cars in your area and know if you'd be getting a good deal or a bad deal.

Interesting culture here - super engineer-centric, features tend to be outlined and handed to coders rather than having a lot (or, any) independent graphic design work beforehand. Plus they have come up with solid answers to problems I've seen plaguing other places I've worked: for example, the way developers too often play with "toy" databases that don't reflect what's going on production. For CarGurus, there are 3 options for our remote dev machines: slice, which is that minimalist subset that is sometimes good to work with on the server side, staging, which is a local weekly copy of production, and shared staging, which is the same but doesn't require everyone to do as much maintenance.

The technology is a mix of proven and reliable and more cutting edge. (Cutting-edge-wise I'm so relieved they're going with React and bypassed the whole Angular thing entirely) On the server, that means some older stuff like Struts and FreeMarker Templating; but both are actually pretty good at what they do. FreeMarker predates JSPs but is a now a well maintained Apache project.

Still, it can be a little arcane. One problem was I wanted to set a variable on the FreeMarker side for Javascript to read as a boolean, but to have the absence of that variable be smoothly treated as 'false'. The code for that turned out to be:

<script>
var isModal = ${(feedbackAsModal?has_content)?then(feedbackAsModal?c,'false')};
</script>

A little wordy but not too bad.

Oh, plus CarGurus bring in lunch for everyone every day, so that's a plus, though I still haven't quite worked out how to manage my calorie counting...

UPDATE:
Senior coworker Jasper suggest:
var isModal = ${(feedbackAsModal!false)?string?js_string};

For me the challenge is remembering that FreeMarker is Java-y in its view of typing, even though it doesn't always look it- it kind of feels like other duck-typed languages I have more familiarity with, plus default variable assignments don't have to specify a type.

As I read through the FreeMarker docs, other idiosyncrasies people here have pointed out include "Freemarker has no default printing of booleans, you need to explicitly use ?string". Also it kinda hates null values - the ! operator is important, in that earlier example, with its meaning "use this substitute if the actual value is null"

No comments:

Post a Comment