Is it possible to use razor syntax in Javascript files?

后端 未结 3 1594
既然无缘
既然无缘 2021-01-05 08:58

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

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-05 09:33

    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:

    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 ...
      });
    });
    

提交回复
热议问题