Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why won't Razor parse this in html mode?

I'm making a reusable package and in order to get the client side to work both with straight javascript and module loaders I have a code paths that requires me to document.write out script tags.

In my razor view I have something like this:

<script>
   ...
   document.write([
       '<script type="text/javascript" src="~/Oaf/SlimHeader/Media/Scripts/jquery-1.9.1.min.js"></script>',
       '<script type="text/javascript" src="~/Oaf/SlimHeader/Media/Scripts/jquery-migrate-1.2.1.min.js"></script>',
   ].join('\n'))
   ...
</script>

Which Razor refuses to interpret in html mode:

Parser Error Message: Unterminated string literal. Strings that start with a quotation mark (") must be terminated before the end of the line. However, strings that start with @ and a quotation mark (@") can span multiple lines.

indicating the error is in the first script tag. This is javascript, I don't want Razor involved at all! (Ok, it would be nice if it parsed the ~ but honestly I can take care of that myself).

I've tried prefixing every line with @: and surrounding the whole thing in @" ... "@ but neither seems to work.

like image 581
George Mauer Avatar asked Oct 26 '25 02:10

George Mauer


2 Answers

This is not a razor issue, this code is invalid even in a simple HTML file, and will cause problems in the browser.

The solution is to:

var a = '<script><' +' /script>';

The bug has been closed as by design.

like image 64
Yishai Galatzer Avatar answered Oct 27 '25 15:10

Yishai Galatzer


Thanks to Aron who got me to pare this down thereby prompting me to discover the answer.

Pared down the broken code looked like this (I hadn't included the if in the question):

@if (true) {
    <script type="text/javascript">
        var a = '<script></script>';
    </script>
}

something in the interplay between the @if and the <script> tag in a sting just does not sit well. If I force text mode on each line inside the if by prefixing with @: then it works.

In the original question the solution it to prefix every line inside the Razor block with @:. Surrounding in a <text> block will not work. If you don't prefix every line with @: then you will get a parsing error very possibly for a line that was prefixed.

Seems like a bug with Razor. Will report it.

like image 29
George Mauer Avatar answered Oct 27 '25 15:10

George Mauer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!