I have a controller action which returns JSON with a rendered template. This template uses date picker form fields. How can the date picker JS be initialized since the html is returned through JSON. I would have thought since the date picker field includes the necessary JS within {%js%} tag during template render it would be initialized. Could it be the timing of render vs adding the template html to the DOM? (Craft 3)

$view = $this->getView();

$html = $view->renderTemplate('_modal',['values' => $values, 'siteId' => $siteId]);
$headHtml = $view->getHeadHtml();

return $this->asJson(['html' => $html, 'headHtml' => $headHtml]);

1 Answer 1


Since your controller returns json you'll probably have a Javascript function that calls this controller so you can initialize it at the moment you receive the html.

Besides that you can as well include Javascript in your Craft::$app->getView()->registerJs class.

  • So the JS included in the DatePicker field macro won't be executed therefore I will need to initialize either in the JS function or using getView()->registerJs?
    – a-am
    Apr 11, 2018 at 20:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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