Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript code in <script> element within VB Razor

I'm trying to include some JS in a view within a Razor conditional, but it keeps trying to interpret my JS as VB:

@If includeMoreJs Then
    @<script type="text/javascript" src="/some-js-file.js"></script>
    <script type="text/javascript" src="/some-other-js-file.js"></script>
    <script type="text/javascript">
        function someFunction(p) {
            if (p) foo();
            else bar();
        }
    </script>
End If

I've also tried this with the <text> psuedo element as described here: Using Razor within JavaScript

@If includeMoreJs Then
    <text>
    <script type="text/javascript" src="/some-js-file.js"></script>
    <script type="text/javascript" src="/some-other-js-file.js"></script>
    <script type="text/javascript">
        function someFunction(p) {
            if (p) foo();
            else bar();
        }
    </script>
    </text>
End If

but still no luck... How can I get VB to leave my JS alone?

like image 931
Casey Rule Avatar asked Jun 22 '26 20:06

Casey Rule


1 Answers

OK having forced myself to create my first ever .vbhtml file, and googling around, you were very nearly there with the <text> block.

This page is a pretty good resource for VB Razor syntax.

There are two ways around this, depending how much html you have in your @If:

Option 1: @:

This is needed on every line so generally you would only use it if there is only one line in your If:

@If includeMoreJs Then
    @:<script type="text/javascript" src="/some-js-file.js"></script>
    @:<script type="text/javascript" src="/some-other-js-file.js"></script>
    @:<script type="text/javascript">
    @:    function someFunction(p) {
    @:        if (p) foo();
    @:        else bar();
    @:
    @:</script>
End If

.. Very pretty

Option 2: @<text>

Because VB can have XML as stated in this answer, a plain <text> will be interpreted as VB code, not razor. So in VB, compared to C#, you need to use @<text> to have a block of HTML:

@If includeMoreJs Then
    @<text>
    <script type="text/javascript" src="/some-js-file.js"></script>
    <script type="text/javascript" src="/some-other-js-file.js"></script>
    <script type="text/javascript">
        function someFunction(p) {
            if (p) foo();
            else bar();
        }
    </script>
    </text>
End If

This parses fine.

like image 130
Rhumborl Avatar answered Jun 25 '26 10:06

Rhumborl