The Razor engine only works with a page, not with javascript files.
You can write your own parser that will trigger the viewer against any javascript files before serving them, and I assume that any attempt to do this would be a very useful open source project.
However, the simplest solution that comes to mind (if these variables are not semantically related to any DOM elements) is to simply declare and initialize your variables on the page (or on the partial part with the part included) and your javascript (in .js
) depends on the definition of these variables.
If the variables you need are logically linked to DOM elements, I prefer to use the data-*
attributes to data-*
them, so your javascript can be used by html, and not vice versa. For example, if you have a content area that should be automatically updated using 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');
Rich o'kelly
source share