How can I see all variables available inside a Velocity Template? - templates

Is it possible to display all variables available inside a Velocity Template?
Let's say 1 developer pass 2 values to template: $headline and $body. Another developer has to deal with those 2 variables. How would he know names of those variables?
Right now we use 3 solutions:
we simply say what variables are present on templates
we agreed with all developers that all data we pass to template should be included into 1 map ($data)
developer that pass variables to templates has to update template as well and describe all the fields available on it.
I'm looking for way to do this correctly. Right now I'm not really satisfied with all approaches, but 2-nd looks like most preferable.

The short answer is:
$context.keys
The variables and "tools" are accessed by the templates via the velocity "context". If the context tool is available, you can request the list of variables via $context.keys. If not, you need to add the tool ContextTool to the context. How this is done depends on your application.
Although it's technically possible to list all keys in the context, I'm not sure it's also good practice in the situation you describe.

Related

Disabling the implicit this in C++

I've been handed a legacy C++ application to patch and add some new features, and I'm having a terrible time following some of the code, as it makes fairly extensive use of globals, huge #define macros and many extremely tersely named variables/functions (3 letter functions from 2 inheritance levels up, etc...). As such, determining the source of many of the functions or variables is rater challenging.
It also uses Hungarian notation.... sometimes (m_Thingie is a member variable, but sometimes so is thingie).
Is there any way to make it so class member access without specifying this-> fails? That would let me use the compiler to effectively determine variable source.
I don't mind if it's a horrible hack, if I can turn it on for a little while when doing refactoring, and then off for any release compilation, that would be fine.
Pick an IDE with advanced colorization, Visual Studio can do it then if you're already using it you don't need to learn anything else.
Click Tools menu then click Options.
Expand Environment settings group from the list in the left and select Fonts and Colors.
Scroll down Display items in the right panel until you find C++ ... items. There you can change settings for things you need (and more):
Change settings to highlight variables and functions according to your needing. Be aware that you can change only color (background and foreground) but size is shared. Too many colors will confuse you then you may need to make some tests before you find right combination for you.
Final result may be:
In this example you can see different colors for:
Local variables.
Global functions (anything declared outside a class).
Function parameters.
Member functions (you may also set a different color for static member functions).
Fields (you may also set a different color for static class fields).
Global variables.
Macros.
Of course literals (string, characters and numbers), user types and enumerations can have their own color combination (also specialized for templates). When you're done with refactoring you can restore default settings clicking on Use Defaults.

Preserve structs data for using it later

I'm learning golang - coding small web blog, and writing router(I know there are available few - gorilla mux, martini, etc).
I have simple struct
type Routes struct {
method string
pattern string
handler Handler
}
and some regex matchers. But i can't understand how do i keep all routes that i will define in one place. Is using slice of structs good idea(like
[]Routes) to keep them all together?
P.S. This is meant for personal understanding of how it all works together
Your question is not really well defined. You told us you want to implement routing functionality based on regular expressions, but you haven't told us what kind of tasks you want to achieve which greatly influence the optimal or best data structure to be used.
You already mentioned you know about a lot of other implementations which are open source, maybe you should check their sources.
This answer might also be a help to you which shows a simple implementation of a basic implementation how to do routing functionality using regular expressions.
If you just want to be able to register regular expressions which if matched by the request path and then forward the serving to a Handler, yes, storing the "rules" in a []Routes is a viable and simple option.
Things to keep in mind:
I would definitely compile the regexp in advance and store the result and not compile them each time which is an awful waste of resources. So your Routes struct should contain a field of type *regexp.Regexp instead of the pattern (you can keep the string pattern too e.g. for debugging purposes).
If your Routes struct grows bigger, I would consider storing pointers in the slice and not struct values, e.g. []*Routes because each time when you loop over them (e.g. in each request to see which matches) or whenever you create a local variable from one of the Routes, a copy is made from the values. Copying large struct is inefficient compared to copying a pointer which is fast.

Famo.us: different ways of creating and calling functions

Hoping someone can provide an explain-like-I’m-five elucidation of the difference between the following types of functions within Famo.us, and when it’s appropriate to use them:
sampleFunction() {}
_sampleFunction() {}
SampleView.prototype.sampleFunction() {}
.bind and .call are also thrown around a lot…I understand them vaguely but not as concretely as I’d like. That might be a different question, but please feel free to use them in your explanation!
Apologies for the vagueness...wish there was more regarding this in famo.us university.
None of what you're looking at is syntax specific to Famo.us. It's actually common, if intermediate level, VanillaJS.
The _ is simply a coding convention to denote that a specific function should belong to the parent scope (ie a member/private function, whatever you prefer to call it). Javascript doesn't really have support for encapsulation - the act of blocking other classes and objects from accessing another class's functions and variables. While it is possible, it's quite cumbersome and hacky.
You'll see that Famo.us uses the underscore convention to denote that a function is a member of the class using it. Some of these functions are actually just aliases to the actual Javascript native function, for example ._add actually just call's Javascript's .add method. Of course, ._add could be updated in the future on Famo.us's end to do more in the future if that's required. You really wouldn't want to try and write over the native Javascript add. That's super bad.
The other upshot is that you can document that class and say that you can and should use the _add method for a specific purpose/scenario. You'll see that in the API docs.
Understanding prototype is a core part of what it means to be a Javascript Programmer, after all, it is a prototype driven language. MDN has a much better explanation than anything I can offer here but it's basically at the core of your classes.
If you want to extend off of an existing class (say, create your own View or Surface type) you would extend it's prototype. Check out Famous Starter Kit's App examples and see how many of them create an "AppView" class, which takes the prototype of the core View, copies it for itself, and then adds it's own functions, thus extending View without ruining the original copy.

Flexible application configuration in C++

I am developing a C++ application used to simulate a real world scenario. Based on this simulation our team is going to develop, test and evaluate different algorithms working within such a real world scenrio.
We need the possibility to define several scenarios (they might differ in a few parameters, but a future scenario might also require creating objects of new classes) and the possibility to maintain a set of algorithms (which is, again, a set of parameters but also the definition which classes are to be created). Parameters are passed to the classes in the constructor.
I am wondering which is the best way to manage all the scenario and algorithm configurations. It should be easily possible to have one developer work on one scenario with "his" algorithm and another developer working on another scenario with "his" different algorithm. Still, the parameter sets might be huge and should be "sharable" (if I defined a set of parameters for a certain algorithm in Scenario A, it should be possible to use the algorithm in Scenario B without copy&paste).
It seems like there are two main ways to accomplish my task:
Define a configuration file format that can handle my requirements. This format might be XML based or custom. As there is no C#-like reflection in C++, it seems like I have to update the config-file parser each time a new algorithm class is added to project (in order to convert a string like "MyClass" into a new instance of MyClass). I could create a name for every setup and pass this name as command line argument.
The pros are: no compilation required to change a parameter and re-run, I can easily store the whole config file with the simulation results
contra: seems like a lot of effort, especially hard because I am using a lot of template classes that have to be instantiated with given template arguments. No IDE support for writing the file (at least without creating a whole XSD which I would have to update everytime a parameter/class is added)
Wire everything up in C++ code. I am not completely sure how I would do this to separate all the different creation logic but still be able to reuse parameters across scenarios. I think I'd also try to give every setup a (string) name and use this name to select the setup via command line arg.
pro: type safety, IDE support, no parser needed
con: how can I easily store the setup with the results (maybe some serialization?)?, needs compilation after every parameter change
Now here are my questions:
- What is your opinion? Did I miss
important pros/cons?
- did I miss a third option?
- Is there a simple way to implement the config file approach that gives
me enough flexibility?
- How would you organize all the factory code in the seconde approach? Are there any good C++ examples for something like this out there?
Thanks a lot!
There is a way to do this without templates or reflection.
First, you make sure that all the classes you want to create from the configuration file have a common base class. Let's call this MyBaseClass and assume that MyClass1, MyClass2 and MyClass3 all inherit from it.
Second, you implement a factory function for each of MyClass1, MyClass2 and MyClass3. The signatures of all these factory functions must be identical. An example factory function is as follows.
MyBaseClass * create_MyClass1(Configuration & cfg)
{
// Retrieve config variables and pass as parameters
// to the constructor
int age = cfg->lookupInt("age");
std::string address = cfg->lookupString("address");
return new MyClass1(age, address);
}
Third, you register all the factory functions in a map.
typedef MyBaseClass* (*FactoryFunc)(Configuration *);
std::map<std::string, FactoryFunc> nameToFactoryFunc;
nameToFactoryFunc["MyClass1"] = &create_MyClass1;
nameToFactoryFunc["MyClass2"] = &create_MyClass2;
nameToFactoryFunc["MyClass3"] = &create_MyClass3;
Finally, you parse the configuration file and iterate over it to find all the entries that specify the name of a class. When you find such an entry, you look up its factory function in the nameToFactoryFunc table and invoke the function to create the corresponding object.
If you don't use XML, it's possible that boost::spirit could short-circuit at least some of the problems you are facing. Here's a simple example of how config data could be parsed directly into a class instance.
I found this website with a nice template supporting factory which I think will be used in my code.

Django templatetag scope forcing me to do extra queries

The problem is that if I call a templatetag into a block
and it fills me a variiable with the usual context[varname]=something,
then if I need that variable into another block, I have to call the
templatetag again. This for me means extra db queries, which is really
something I'm trying to avoid.
This templatetag is called in a base template which is extended by
many other templates, so I can't just change all the views to pass
something to the context, it makes no sense (WET principle?)
Even a context processor would be not good because I don't want to
call it for every page rendered in the site, even the ones not based
on that template.
I was thinking about writing a templatetag which would use the
internal context structures to put the variable in a global context,
but I'd feel too guilty doing it.
How would you solve this problem?
You said, "This templatetag is called in a base template which is extended by many other templates."
The question is: is this tag called from within a named block? If it is then you have a couple of potential problems.
{% block %} pushes a new dict on the Context stack and pops it off when it reaches the matching `{% endblock %}'. This means any context value created while in the block has essentially gone out of scope on block exit.
If this block is overridden by some other template that extends the base template, the value may not be available at all unless you do a {{block.super}}, and even then I'm not certain the value will be available to the template doing the extending.
If the tag is not called from within a {% block %} then the context value should be available to all of the code that follows it, either in the base template, any included templates and (I think) any extending templates.
This is one of those cases where building a set of careful tests will probably save you time and tears.
Alternatively, if you are always accessing this value, you could just put it in a context processor so that its availability is guaranteed.
Update for comments: OK, time to bring in the big guns! One of the most irritating, long-standing bugs in Django templates is that callables (ie. functions) that are top-level context values (as opposed to functions that are dict-values/methods of context values) are not called! This ticket is over 2 years old and takes about 10 lines of code to fix. We have several heavy-weight DB calls that we only want to happen if the template cache has expired. So we a) MonkeyPatched the template _resolve_lookup() code to fix the callable problem, and then b) curry functions to have all of the necessary parameters if needed, because you can't pass params to functions in the template "language".
I think you've accurately described the limitations in this situation. The most maintainable solutions will likely involve some restructuring of your template inheritance chain, though its hard to say without knowing the details. Can you introduce a new template in the inheritance hierarchy, probably somewhere near the top of the pyramid but so it only is inherited by templates that need this data, with a single block that encompasses the entire region within which you need this data? That big block can then be subdivided into smaller blocks that inheriting templates will override. If you call your templatetag at the beginning of that block, all blocks within it (including in inheriting templates) will have access to the data.
Update: I can't say much without seeing your templates, but introducing a new template in the middle of an inheritance chain very rarely involves "changing all the templates," in a sane inheritance structure it often can be done with changes to only one or two other templates. And I think what I am suggesting is actually not a hack, it's just better design. If you need a certain piece of data in certain parts of your site and not other parts, there should be a specific single template you can point to and say "this template represents the logical layer at which this piece of data is introduced, and encompasses the parts of the site where that data is needed."
Are you just trying to keep down the number of database queries or are you looking for a clever solution?
If it's the former, I would definitely go with caching. Would fragment caching work in your case? If not, perhaps you could put the caching in the template tag code (assuming it's not one of Django's own template tags your using)?
Just came across this trick from Liviu, Agile Bear (all credit goes to him)
Instead of doing
context['some_var']='some value'
do
context.dicts[0]['some_var']='some value'
May not be a by-the-book-coding-practice but works well enough