XF 2.0 Dump all template variables to javascript console

infis

Well-known member
In 2.0 we do not have the variable $__params. Therefore, in order to dump all variables, you need to add a class extension XF\Template\Templater.

Create our class. For example src/addons/InfisJSC/XF/Template/Templater.php:
PHP:
<?php
namespace InfisJSC\XF\Template;

class Templater extends XFCP_Templater
{
    public function renderTemplate($template, array $params = [], $addDefaultParams = true)
    {
        $__vars = $params;
        if ($addDefaultParams)
        {
            $__vars = array_merge($this->defaultParams, $__vars);
        }
        $params['__vars'] = $__vars;
        return parent::renderTemplate($template, $params, $addDefaultParams); // TODO: Change the autogenerated stub
    }
}

Now the class has been created, we can create the class extension on the Admin CP > Development > Class extensions > Add class extension page.

All you need to do is enter the base class name (XF\Template\Templater) in the first field, and the extended class name (which you just created) in the second field (InfisJSC\XF\Template\Templater) and click the "Save" button.

And now create class for callback. For example src/addons/InfisJSC/Helper.php:
PHP:
<?php
namespace InfisJSC;

class Helper
{
    static function convertUTF8 (&$item, $key)
    {
        if (gettype($item) == 'string')
        {
            $item = iconv('UTF-8', 'UTF-8//IGNORE', $item);
        }
    }

    /**
     * Callback function for output dump to javascript console
     *
     * Example:
     * <xf:callback class="\InfisJSC\Helper" method="getLog" params="$__vars">$__vars</xf:callback>
     *
     * @param $content
     * @param $params
     * @param $template
     * @return string
     */
    public static function getLog ($content, $params, \XF\Template\Templater $template)
    {
        array_walk_recursive($params, array(__CLASS__, 'convertUTF8'));

        $result = \XF\Util\Json::jsonEncodePretty($params);

        if (!empty($content))
        {
            $variableName = '\'' . $content . ':\', ';
        } else {
            $variableName = '';
        }

        return '
            <script>
                var jObject = ' . $result . ';
                console.log(' . $variableName . 'jObject);
            </script>
        ';
    }
}

Now we can insert in template this call:
Code:
<xf:callback class="\InfisJSC\Helper" method="getLog" params="$__vars">$__vars</xf:callback>

I did not find how to add the output of the template name. If anyone tells me, I will be grateful.

For 1.5 example https://xenforo.com/community/threads/dump-all-template-variables-to-javascript-console.145532/
 
Top Bottom