Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
301 views
in Technique[技术] by (71.8m points)

python - Chameleon templates for javascript files?

I am developing a simple pyramid application where I am using JQuery to do AJAX requests. I have until now had my javascript code within my chameleon templates. Now I want to extract my javascript into another location (e.g. as static resources).

My problem is that I find my javascript code relies on dynamically generated content like so:

$.post("${request.route_url('my_view')}",{'data': 'some data'}, function(html){
    $("#destination").html(html);
});

The dynamic element being:

"${request.route_url('my_view')}"

Which is calling the route_url method of the request object within the template.

Is there a recognised pattern for separating such javascript files into their own templates and providing routes and views for them or do I simply keep my javascript in my page template?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...