#define JS(...) #__VA_ARGS__ const char *someJs = JS( /* This may contain any valid JavaScript */ var Foo = function(java, script, here) { var a, b; this.eatCrocodile = function(d) { d.innerHTML = "Eating it now"; } }; );
Since long, Wt embedded snippets of JavaScript code (e.g. used for implementing the layout managers) directly in the C++ source code as string literals. This was not very developer friendly, and it also did not allow for using a minifier to compress the JavaScript.
The latest Wt git contains the following nice (and hacky!) solution. It is based on the following idea (but more elaborated):
#define JS(...) #__VA_ARGS__ const char *someJs = JS( /* This may contain any valid JavaScript */ var Foo = function(java, script, here) { var a, b; this.eatCrocodile = function(d) { d.innerHTML = "Eating it now"; } }; );
Thus, by defining a macro which takes variable arguments (to allow for ‘,’ in the JavaScript code) and pastes them into a string, you can put multi-line JavaScript statements or expressions inside your C++ code, which are formatted by the compiler into a string literal.
This works (incidently!) because JavaScript also requires that brackets are balanced, and uses the same syntax for comments and string/char literals.
Snippets of JavaScript code are served by Wt piecewise when needed and inline to avoid an additional round-trip. We use this trick to include (minified) JavaScript files directly into C++ code for optimized released builds, while reading the same JavaScript files from disk during debug builds. In this way, we avoid a rebuild when going through trial-and-error cycles trying to make our JavaScript work properly on all browsers, and benefit from a minifier (we are currently using Google Closure compiler) for hassle-free release builds.
Sometimes, we love the preprocessor that we all hate.
str = str.replace(/(\d+)\.\d+/, '$1.');