How to put HTML on the page with SSJS without quoting it

In the series of articles comparing and contrasting WCTL and SSJS, one of the points I made was that with SSJS, all html going to the response buffer has to be quoted, like this:

+ 'some text';

or this

var bb = new ByteBuffer();
bb += 'some text';
return bb;


But in the fine print on the summary table, I said there was an exception I would write about later.  Well, later is now.

But first, let's talk best practices. As illustrated above, there are two ways to get HTML into the response buffer:
  1. response.append( 'some text' ), or use the shortcut for that, + 'some text';
  2. concatenate everything into a ByteBuffer() and return that at the end of the function or page
Generally speaking, method #2 is better.  You avoid a lot of weird issues when mixing SSJS and WCTL related to the order in which things appear on the page, and there is a slight performance advantage.

So with that out of the way, let's look at that exception.  As it turns out, you can use pairs of %%'s (remember those from WCTL?) to delimit blocks of plain HTML to go to the response buffer.  And of course, you can include client-side JavaScript in that block if you want to.  But you can't replace any dynamic variables.  (So you might as well put that client-side JS into a separate file, it seems to me, and save the bandwidth).

The other thing about using this method is that the HTML inside those pairs of %%'s goes immediately into the response buffer as if you had +'d or response.appended it. Try as you might, you can't do something like this, because the text "this will not work" will appear immediately on the page.

var myHTML = %% <b>this will not work</b> %%

So that means you can't use it with the better method #2 above.  Keep it under your hat in case you run across the perfect use for it, but in my experience it's not all that helpful.

No comments:

Post a Comment