I have several modules for a given position, but I only want to display one of them (selected randomly) on the front-end in a Gantry template.
Is there any way to do this?
Joomla Stack Exchange is a question and answer site for Joomla! administrators, users, developers and designers. It only takes a minute to sign up.
Sign up to join this communityI have several modules for a given position, but I only want to display one of them (selected randomly) on the front-end in a Gantry template.
Is there any way to do this?
Have a look at the Module Helper documentation.
getModules()
: Get modules by positiongetModules(string $position) : array static
since 1.5Arguments
$position string The position of the moduleResponse array
An array of module objects
and
renderModule()
: Render the module.renderModule(object $module, array $attribs = array()) : string static
since 1.5Arguments
$module objectA module object.
$attribs array An array of attributes for the module (probably from the XML).Response string
The HTML content of the module output.
This means that after declaring use Joomla\CMS\Helper\ModuleHelper;
, you can simply:
Code:
$position = 'position-2';
$modules = JModuleHelper::getModules($position);
echo JModuleHelper::renderModule($modules[array_rand($modules)]);
This is effectively an extension of FFrewin's answer from 2014.
In your template, write the jdoc placeholder.
<jdoc:include type="modules" name="position-2" />
A short list of relevant pages to reference:
If you're after a less code heavy way of doing it, you could use a mix of Regular Labs Modules anywhere and Regular Labs Articles Anywhere.
{articles category="Random Modules" ordering="random" limit="1"}[title][fulltext]{/articles}