Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use razor syntax in Javascript files?

I'd like to use razor syntax inside my Javascript files. Is this possible without including the javascript inline into the page?

like image 264
Tjaart Avatar asked Jan 26 '12 10:01

Tjaart


People also ask

Is razor a scripting language?

Razor is not a programming language. It's a server side markup language.

What is Razor syntax?

Razor syntax is a simple programming syntax for embedding server-based code in a web page. In a web page that uses the Razor syntax, there are two kinds of content: client content and server code.

Where do I put JavaScript in Blazor?

Inject a script into the <head> element markup that references a custom JS file after starting Blazor by calling Blazor.start().then(...) . Place the script ( <script>...</script> ) inside the closing </body> tag after the Blazor script is loaded.


2 Answers

I found a razor engine RazorJS on nuget that solves @ in js files
The owner blog and explanations about the package abilities
The Nuget package

see more in this question

like image 91
gdoron is supporting Monica Avatar answered Nov 12 '22 01:11

gdoron is supporting Monica


The Razor engine only runs against the page, not any included javascript files.

You could write a custom parser that will run the view engine against any javascript files before serving them, and I imagine any attempt to do so would be a very useful open source project.

However, the simplest solution that comes to mind (if these variables are not sematically linked to any DOM elements) is to simply declare and initialise your variables in the page (or in an included partial page) and your javascript (in .js files) relies on these variables being defined.

If however the variables that you require are logically associated with DOM elements, I prefer to use data-* attributes to define these, this way your javascript can be consumed by the html, rather than the other way around. For example, if you have a content area that should be automatically updated by javascript (using jQuery as an example here):

HTML:

<div data-auto-refresh="pathToContent" data-auto-refresh-milliseconds="1000"></div>

Javascript:

$(function() {
  $('[data-auto-refresh]').each(function() {
    var self = $(this);
    var url = self.data('auto-refresh');
    var interval = self.data('auto-refresh-milliseconds');
    // Code to handle refresh here ...
  });
});
like image 30
Rich O'Kelly Avatar answered Nov 12 '22 01:11

Rich O'Kelly