Search code examples
phpmodxmodx-revolution

get template variable value on each page modx revolution


I use modx and, to be honest, I am new to this CMS. I want to show corresponding Template Variable's value on each page. Here is my code written in the snippet:

<?php
if ( isset($modx->documentObject['PDF-Resource-Url'][1]) && !empty($modx->documentObject['PDF-Resource-Url'][1]) ) {
echo '<li class="related-link slide expanded"><a href="' . $modx->documentObject['PDF-Resource-Url'][1] . '" target="_blank">Pdf</a></li>';
}
?>

But it returns empty output. I use the latest version of modx revolution. I think that maybe this is the reason why I see empty output.

Thanks for helping!


Solution

  • It looks like you're using methods from MODX Evolution. Revolution is different so it would be a good idea to familiarise yourself with the documentation. I've provided some links below.

    To get a template variable value using the API is simple:

    $value = $modx->resource->getTVValue('tv-name');
    

    $modx->resource always contains the object for the current resource.

    Your example would become:

    $output = '';
    
    $url = $modx->resource->getTVValue('PDF-Resource-Url');
    if (!empty($url)) {
        $output = '<li class="related-link slide expanded"><a href="' . $url . '" target="_blank">Pdf</a></li>';
    }
    
    // always return output rather than echoing to page
    return $output;
    

    How to get the current resource object: http://rtfm.modx.com/revolution/2.x/making-sites-with-modx/structuring-your-site/resources

    How to retrieve template variables: http://rtfm.modx.com/revolution/2.x/making-sites-with-modx/customizing-content/template-variables/accessing-template-variable-values-via-the-api

    Basic snippet development: http://rtfm.modx.com/revolution/2.x/developing-in-modx/basic-development/snippets