Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

javascript scope #92

Closed
smcmurray opened this issue Sep 19, 2013 · 2 comments
Closed

javascript scope #92

smcmurray opened this issue Sep 19, 2013 · 2 comments

Comments

@smcmurray
Copy link

I'm trying to load subtemplates dynamically. So I created a small function that retrieves a template file and compiles it. Then I use that function inside templates. So I have code that looks like this:

  var cache = {};
  var compile = function(path){
      if (!(path in cache))
        cache[path] = doT.template($.ajax(path, {async: false}).responseText);
      return cache[path];
  };

  var people = [
    {
      "name": "Alice",
      "gender": "female"
    },
    {
      "name": "Bob",
      "gender": "male"
    }
  ];

  $.get("/templates/list.dot", function(r){
    var t = doT.template(r);
    t(people);
  });

list.dot could look like this:

{{~it :person}}
  {{=compile("/templates/"+ person.gender + ".dot")(person)}}
{{~}}

The list.dot template compiles, but the resulting function fails to run, complaining that "compile is not defined."

How do I get compile() into scope?

@smcmurray
Copy link
Author

The best I could come up with was to change templateSettings.varname to 'it, compile', then pass in the compile function.

I'd love to be enlightened with a better way.

@epoberezkin
Copy link
Collaborator

Two other approaches are either adding them to data properties or passing context into templating function and pass it through to sub-templates (using .call/.apply).

Probably worth adding to doT 101 together with recursion #205.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants