posted by admin
on Tue, 08/27/2013 - 22:02
ZF2 provides HeadScript and InlineScript Helpers to inject <script> elements in the template typically located inside the <head> tag, or at the very bottom of the closing </body> tag. To inject Title, Meta Keywords, Meta Description, headScript, and inlineScript in the view:
<html> <head> <?php echo $this->headTitle(); ?> <!-- Display Meta Keywords and Description along with Viewport --> <?php echo $this->headMeta()->appendName('viewport', 'width=device-width, initial-scale=1.0') ?> <meta charset="utf-8"> <?php echo $this->headScript(); ?> </head> <body> ... <?php echo $this->inlineScript(); ?> </body> </html>
And, you'll assign script tag in the Controller like this:
public function indexAction() { $renderer = $this->getServiceLocator()->get( 'Zend\View\Renderer\PhpRenderer'); $renderer->headTitle('Head Title'); $renderer->headMeta()->appendName('keywords', 'Meta Keywords'); $renderer->headMeta()->appendName('description', 'Meta Description'); $env = getenv("APPLICATION_ENV"); if ($env == "production") { // Only add the script in the "production" environment. $script = $this->getServiceLocator()->get('viewhelpermanager') ->get('inlineScript'); // No need to add beginning or ending <script> tags, as they // will be automatically inserted by the appendScript method. $script->appendScript( '$(document).ready(function() { alert("Hello"); });', 'text/javascript', array('noescape' => true)); // Disable CDATA comments } return new ViewModel(); }
Comments
Add new comment