Fix infinite recursion bug with SQL and Cache panels

Move the stack trace loop into a utility method. Check for calls to get_template_context.

I wasn't sure about the logic to check the current file. I had it done programmatically, but that was ugly and probably more confusing than just checking the string value of the name.

Closes #598