1

I'm currently developing a module that contains a custom field and I'd like to create a template to be used in the getInputHtml method.

I try using the Craft::$app->view->renderTemplate method to render a template in the "resources" folder of my module, but Craft does not seem to find the template. How should I specify the path to the template from this module?

2

You need to include your template roots Enhancing a Craft CMS 3 Website with a Custom Module

public function __construct($id, $parent = null, array $config = [])
{
    Craft::setAlias('@modules/sitemodule', $this->getBasePath());
    $this->controllerNamespace = 'modules\sitemodule\controllers';

    // Base template directory
    Event::on(View::class, View::EVENT_REGISTER_CP_TEMPLATE_ROOTS, function (RegisterTemplateRootsEvent $e) {
        if (is_dir($baseDir = $this->getBasePath().DIRECTORY_SEPARATOR.'templates')) {
            $e->roots[$this->id] = $baseDir;
        }
    });

    // Set this as the global instance of this module class
    static::setInstance($this);

    parent::__construct($id, $parent, $config);
}
2
  • Thank you Robin for your swift reply. I've added the code to the main module file, but I'm not sure what path I should use to render the template. Do you have an idea? – kant312 Aug 2 '18 at 8:11
  • 1
    If your module is called my-module in your bootstrap file and contains a file modules/my-module/src/templates/fields/myField.twig the path will be my-module/fields/myField.twig – Robin Schambach Aug 2 '18 at 8:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.