Chameleon templates for javascript files?

ぃ、小莉子 提交于 2019-11-29 07:33:09

Yes; you generally put context-specific information like expanded routes into the templates and access this information from your (static) JavaScript libraries.

Including the context info can be done in various ways, depending on taste:

  1. You could use a data attribute on a tag in your generated HTML:

    <body data-viewurl="http://www.example.com/route/to/view">
        ...
    </body>
    

    which you then, in your static JS code load with the jQuery .data() function:

    var viewurl = $('body').data('viewurl');
    
  2. Use a made-up LINK tag relationship to include links in the document head:

    <head>
        <link rel="ajax-datasource" id="viewurl"
              href="http://www.example.com/route/to/view" />
        ...
    </head>
    

    which can be retrieved using $('link#viewurl').attr('href'), or $('link[rel=ajax-datasource]').attr('href'). This only really works for URL information.

  3. Generate JS variables straight in your template, to be referenced from your static code:

    <head>
        ...
        <script type="text/javascript">
           window.contextVariables = {
               viewurl = "http://www.example.com/route/to/view",
               ...
           };
        </script>
    </head>
    

    and these variables are referable directly with contextVariables.viewurl.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!