I’ve decided to start a new series of ‘quick tip’ posts. Each post will be short and focused on a particular problem, an interesting technique, or to improve your productivity.
What we want to do
Let’s say we have some Javascript code we want to include in our web pages. It’s very common to want to be able to insert dynamic values computed on the server-side into our JS code.
As a very simple use-case, suppose we want to include a script to initialize the Facebook JS SDK into our web page. At the very least we would need to include the app ID.
How to do it
This is the templated JS file we want to include in our web page. It has two placeholders that will be replaced at run-time:
const curr_user_id = ${currUserId};
window.fbAsyncInit = function() {
FB.init({
appId : '${fbAppId}',
autoLogAppEvents : true,
xfbml : true,
version : 'v6.0'
});
};
In order to add this script to our web page, we will create a Wicket behavior class that will be responsible for replacing the placeholder values and adding the script into the <head> tag:
public class InitFbSdkBehavior extends Behavior {
@SpringBean private UserService userService;
@Override
public void renderHead(final Component component, final IHeaderResponse response) {
Map<String, Object> variables = new HashMap<>();
variables.put("fbAppId", FacebookService.getAppId());
variables.put("currUserId", userService.getCurrUserId());
try (PackageTextTemplate template = new PackageTextTemplate(getClass(), "fb_init.js")) {
response.render(JavaScriptHeaderItem.forScript(template.asString(variables), "fb_init"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
Notice that the variables map key names correspond to the names of the placeholders in the script file.
How to use it
Using the InitFbSdkBehavior class is very simple. Whenever you want to include the script in your page just add it:
public class FbTestPage extends WebPage {
public FbTestPage() {
super();
add(new InitFbSdkBehavior());
}
}
The rendered HTML output will look something like this:
<head><script type="text/javascript" id="fb_init">
/*<![CDATA[*/
const curr_user_id = 1
window.fbAsyncInit = function() {
FB.init({
appId : '1321321321',
autoLogAppEvents : true,
xfbml : true,
version : 'v6.0'
});
};
/*]]>*/
</script>
</head>