I’m trying to simplify a complicated design process for my team. Long story short, our server inserts a hidden template section into our single page app, so that we can use DOM nodes instead of JST templates for our Backbone.js app. I’ve discovered that jquery’s .clone() method doesn’t like certain attributes.
When I use $('.mainBillboard').clone(), this:
<div style="background-image: url({{ banner_url }})" id="mainBillboard">
…gets cloned into this:
<div id="mainBillboard" style="">
I’ve seen similar behavior for the src='{{ image_url }}' attribute of image tags.
Note that if I were to leave off an ‘e’ from ‘style’, then jquery would clone the DOM element exactly as it is. I found a way around this for our current needs, but I’m curious why jquery totally culls these attributes specifically. Is this some sort of attack protection (like anti-XSS)?
I’m guessing that you’re using Firefox for your testing. When I use this:
and this:
Demo: http://jsfiddle.net/ambiguous/YEPjL/
in Safari or Chrome, I get the same output for both but when I use Firefox, the second one has an empty
styleattribute. However, if the HTML looks like this:then I get the same output everywhere.
Demo: http://jsfiddle.net/ambiguous/XukCa/
The problem is that
{{ banner_url }}isn’t a valid URL so Firefox is, apparently removing it while it tries to parse the HTML; even though your HTML is inside a hidden a<div>, the browser still has to parse and validate just like it would for some HTML that is being displayed.The usual approach to embedding templates in your HTML is to use
<script>elements to keep the browser from trying to interpret them. I’d recommend that you switch to this structure:So one
<script type="text/html">(or<script type="text/template">if you prefer) for each template and then you can get the content with$('#tmpl-mainBillboard').html()and hand that output to your template engine for parsing.Demo: http://jsfiddle.net/ambiguous/cZzW9/
That last demo produces the same output for the
<script>chunks in Firefox, Chrome, and Safari.