[removed] tag inside jquery template

2019-01-26 03:25发布

问题:

Backgroud:

I have this template that includes videos from youtube being loaded with swfobject.

Question:

Is there a way to include a script tag...

<script type="text/javascript">
</script>

inside a jQuery Template??

<script id="filaVideoTemplate" type="text/x-jQuery-tmpl">
    <!-- Some HTML here -->
    <script type="text/javascript">
        <!-- Some javascript here -->
    </script>
</script>

Obviously it doesn't work directly, is there any way to achive the same thing without the script inside other script?

回答1:

<script id="filaVideoTemplate" type="text/x-jQuery-tmpl">
    <!-- Some HTML here -->
    <script type="text/javascript">
        <!-- Some javascript here -->
    {{html "</sc"+"ript>"}}
</script>

You can use {{html "</sc"+"ript>"}} replace </script>



回答2:

Not sure if this is the only way, but you can insert the script as raw HTML for the template:

<script id="filaVideoTemplate" type="text/x-jQuery-tmpl">
    <!-- Some HTML here -->
    {{html innerScript}}
</script>

Then:

var innerScript = '<script type="text/javascript"><!-- Some javascript here --></script>';
$('#filaVideoTemplate').tmpl({innerScript: innerScript});


回答3:

Ronny Wang's answer offered a good place to start for my problem. However, his solution didn't work for me -- the .. tags in the body of the jQuery template was causing problems on my MVC3 Razor view page.

Fortunately, I stumbled across a solution ( details @ https://github.com/jquery/jquery-tmpl/issues/94 ) that works and requires only a minor change. Here's Ronny's answer, but with a fix that should make it MVC3-compatible:

<script id="filaVideoTemplate" type="text/x-jQuery-tmpl">
    <!-- Some HTML here -->
    <scr{{= ""}}ipt type="text/javascript">
        <!-- Some javascript here -->
    </scr{{= ""}}ipt>
</script>

Looks like both the opening and closing tag just need to be broken up. Hope this helps!



回答4:

<script id="filaVideoTemplate" type="text/x-jQuery-tmpl">
   <!-- Some HTML here -->  
</script>



var data = [{ 'Id': '1', 'Name': 'a' }, { 'Id': '2', 'Name': 'b' }, { 'Id': '3', 'Name': 'c'}];

var renderedHtml = $('<div />').html($('#filaVideoTemplate').tmpl(data)).append(('<script type="text/javascript"><!-- Some javascript here --></endScript>').replace(/endScript/g, 'script')).html();

if data is single not a collection above code is correct. else ( data is collection ) the script tag used to bind multiple times ( data.length times ).



回答5:

not sure what you asking but: you can use ajax request and put your template inside of (js) file . my template_script.js the use ajax like so:

$('the element').load('template_script.js').then( OK , fail );

function OK(){
  do something if request was ok.
}

function fail(){
  do something if request was not ok.
}