在Twig中动态设置未定义的变量

I am researching which template engine to use for mail merging in a project and feel that Twig is probably the best choice.

Obviously with a mail-merge there are thousands of variables and it would be very inefficient to load them all with extensive SQL calls when only a handful will be used in a document. All our variables are in the array form of:

{{table.field}}

What I need to do is when Twig comes across a "table" variable that is not set, it calls a procedure that will populate it with values. This obviously prevents numerous wasteful calls to the SQL database in an attempt to populate every conceivable variable.

How would I go about this in Twig?