I have the following issue, that I need to copy the values of an freemarker list to a javascript array.
currently, I have the following:
var items = [[#list cart.lineItems as item]${item?js_string}[/#list]];
which results in sth like the following:
[LineItemImpl[productId=3e14a4f7-7f35-4010-8346-76b51eec9cb4,variant=ProductVariantImpl[productId=3e14a4f7-7235-4110-8326-76b51eec9cb4,id=1,sku=anySKU,prices=[PriceImpl[currentValue=<null>,value=EUR 19.99000,country=DE,customerGroup=<null>,channel=<null>,discounted=<null>,validFrom=<null>,validUntil=<null>,id=f43967f7-2h73-43ac-a0c0-ea506b9fe66e,custom=<null>]],label=Damen Sport Shirt Rückansicht Größe XS]],availability=ProductVariantAvailabilityImpl[isOnStock=true,restockableInDays=<null>,channels={},availableQuantity=10],isMatchingVariant=<null>,price=<null>,scopedPrice=<null>,scopedPriceDiscounted=<null>,key=<null>,assets=[],attributes=[AttributeImpl[name=color,value={\"key\":\"white\",\"label\":\"Weiß\"}], AttributeImpl[name=Material,value={\"label\":\"Polyester\",\"key\":\"polyester\"}], AttributeImpl[name=Fuer,value=
This contains (nearly at end) the characters { }, where script stops working with error:
Invalid or unexpected token.
I think it's is because of the mentioned characters. How would i additionally escape those characters. Is that possible with the given builtIn functions of ftl, or will I need a more complex approach ?
It seems that you aren't just want to insert some string into the middle of a JavaScript string (that's what ?js_string
is for). You want to convert a bunch of Java objects to JavaScript. Assuming those object are just basic JavaBeans and List
-s/array-s, perhaps you can do it with Jackson or other library that marshal Java objects to JSON. FreeMarker isn't relevant here; if you have JSON, you just insert it without escaping.