Determining a list of missing tokens

108 views
Skip to first unread message

Richard

unread,
Mar 15, 2012, 9:47:00 PM3/15/12
to dotliquid
Is there any way to get a list of tokens used in a template that don't
have a corresponding value?

For instance I'd like to provide a template that has some custom
tokens in it, and prompt users for their values prior to rendering.
The template would contain references to some standard tokens that all
templates support such as {{user.Name}}, {{user.Phone}} etc., but it
could also contain some that aren't in my standard list such as
{{token1}}, {{PageUrl}} etc. that I'd like to detect and then prompt
the user for.

Any ideas?

Tim Jones

unread,
Mar 16, 2012, 12:48:34 AM3/16/12
to dotl...@googlegroups.com
Hi Richard,

Yes, this is possible.

First, define an AddNodesRecursive method:

private static void AddNodesRecursive(Tag tag, List<object> nodes)
{
foreach (var node in tag.NodeList)
{
if (node is Tag)
AddNodesRecursive((Tag)node, nodes);
else
nodes.Add(node);
}
}

Then you can parse the template, recursively grab the parsed nodes, filter to just Variables, and finally get the variable names:

var nodes =new List<object>();
AddNodesRecursive(template.Root, nodes);

var variables = nodes.OfType<Variable>();
var variableNames = variables.Select(v => v.Name);
variableNames = variableNames;

Hope that helps,
Tim

Richard

unread,
Mar 16, 2012, 7:38:22 AM3/16/12
to dotl...@googlegroups.com
Thanks Tim, that definitely helps a ton.

One thing I found though, is that it's only picking up variables that are defined outside of if-then blocks. If I have something like the following then the variable (user.DisplayName) isn't picked up, unless it's used by itself somewhere else in the template.

{% if user.DisplayName == 'Administrator Account' %}
<h1>Big Cheese</h1>
{% endif %}

Tim Jones

unread,
Mar 16, 2012, 9:40:50 AM3/16/12
to dotl...@googlegroups.com
Hi Richard,

That's true. There's also the assign tag, etc. To pick up everything would be more complicated, and not really feasible in DotLiquid at the moment. (For example, the Assign tag stores the RHS of the assignment in a private variable.)

You're welcome to log an issue on GitHub. It's the kind of thing that would be nice to have in v2!

Thanks,
Tim

Richard

unread,
Mar 16, 2012, 10:32:07 AM3/16/12
to dotl...@googlegroups.com
Ok, thanks again. Maybe I'll just have the users enter custom variables under a specific area such as custom.MyVar1 and custom.MyVar2 and then use a combination of your method and another one to parse out any custom.* entries from either the Righthand or Lefthand sides of any if clauses.

Reply all
Reply to author
Forward
0 new messages