doujing4555
2015-11-18 17:30
浏览 58
已采纳

如何在ZF2中添加Javascript和CSS文件到布局

I am trying to learn ZF2 and I just want to specify Javascript and CSS files to be included in my layout. I currently pass an array of paths relative to my public directory to my view and then loop through them. I would like to make use of the built in ZF2 solution using:

$this->headScript();
$this->headStyle();

I have tried many suggested methods on similar questions, but I must not be following them correctly.

One of the solutions I tried which seemed to make sense was here by using either of these in my controller:

$this->getServiceLocator()->get('Zend\View\HelperPluginManager')->get('headLink')->appendStylesheet('/css/style.css');
$this->getServiceLocator()->get('viewhelpermanager')->get('headLink')->appendStylesheet('/css/style.css');

I am not sure what viewhelpermanager it seems like a placeholder the poster used, but I have seen it in more than one question. I went ahead and found the location of Zend\View\HelperPluginManager but that did not work either.

By "not working" I mean my page is displayed without CSS and there is zero output from these:

$this->headScript();
$this->headStyle();

It seems like such a simple task and I do not know why I am having this much of a difficulty.

EDIT #1:

Here is my controller:

<?php
namespace CSAdmin\Controller;

use Zend\View\Model\ViewModel;
use Zend\View\HelperPluginManager;

class LoginController extends AdminController
{
    public function __construct() {
        parent::__construct();
    }

    public function indexAction()
    {
        //Set Action specific Styles and Scripts
        $viewHelperManager = $this->getServiceLocator()->get(`ViewHelperManager`);
        $headLinkHelper = $viewHelperManager->get('HeadLink');
        $headLinkHelper->appendStylesheet('/css/admin/form.css','text/css',array());
        $headLinkHelper->appendStylesheet('/css/admin/styles.css','text/css',array());

        //Override view to use predefined Admin Views
        $view = new ViewModel(array('data'=>$this->data));
        $view->setTemplate('CSAdmin/login/login.phtml'); // path to phtml file under view folder

        //Set the Admin Layout
        $layout = $this->layout();
        $layout->setVariable('layout', $this->layoutVars);
        $layout->setTemplate('layout/CSAdmin/login.phtml');

        //Render Page
        return $view;
    }

My AdminController:

<?php
namespace CSAdmin\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

class AdminController extends AbstractActionController
{
    protected $data = array();
    protected $layoutVars = array();
    protected $viewHelper;

    public function __construct() {
        $this->layoutVars['customStyles'] = array();
        $this->layoutVars['customScripts'] = array();
        $this->layoutVars['miscCode'] = array();
        //$this->viewHelper = $viewHelper;
    }
}

EDIT #2:

@Wilt Error message for the above to controllers: Error message for the above to controllers

Line 19 is

$viewHelperManager = $this->getServiceLocator()->get("ViewHelperManager");

EDIT #3:

There are two modules involved here. Admin and CSAdmin, the controllers from Admin extend the controllers from CSAdmin and all of the controllers from CSAdmin extend a base controller within CSAdmin AdminController. AdminController extends AbstractActionController.

My controller and service_manager arrays for each module.config.php for both modules are below:

Admin:

'service_manager' => array(
    'invokables' => array(
        'CSAdmin\Form\LoginForm' => 'CSAdmin\Form\LoginForm'
    ),
    'factories' => array(
    )
),
'controllers' => array(
    'invokables' => array(
    ),
    'factories' => array(
        'Admin\Controller\Login' => 'Admin\Factory\LoginControllerFactory',
    )
),
// This lines opens the configuration for the RouteManager
'router' => array(
    // Open configuration for all possible routes
    'routes' => array(
        'admin' => array(
            'type' => 'literal',
            'options' => array(
                'route'    => '/admin',
                'defaults' => array(
                    'controller' => 'Admin\Controller\Login',
                    'action'     => 'index',
                ),
            ),
            'may_terminate' => true,
            'child_routes'  => array(
                'home' => array(
                    'type' => 'literal',
                    'options' => array(
                        'route'    => '/home',
                        'defaults' => array(
                            'controller' => 'Admin\Controller\Login',
                            'action' => 'home'
                        )
                    )
                ),
            )
        )
    )
)

CSAdmin:

'service_manager' => array(
    'invokables' => array(
    ),
    'factories' => array(
        'CSAdmin\Mapper\LoginMapperInterface'   => 'CSAdmin\Factory\LoginMapperFactory',
        'CSAdmin\Service\LoginServiceInterface' => 'CSAdmin\Factory\LoginServiceFactory'
    )
),
'controllers' => array(
    'invokables' => array(
    ),
    'factories' => array(
        'CSAdmin\Controller\Admin' => 'CSAdmin\Factory\AdminControllerFactory',
        'CSAdmin\Controller\Login' => 'CSAdmin\Factory\LoginControllerFactory',
    )
 )

EDIT #4:

/module/Admin/src/Admin/Factory/LoginControllerFactory.php:

namespace Admin\Factory;

use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Admin\Controller\LoginController;
use CSAdmin\Service\LoginServiceInterface;

class LoginControllerFactory implements FactoryInterface
{
    /**
    * Create service
    *
    * @param ServiceLocatorInterface $serviceLocator
    * @return mixed
    */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {

        $realServiceLocator = $serviceLocator->getServiceLocator();
        $loginService        = $realServiceLocator->get('CSAdmin\Service\LoginServiceInterface');
        $loginForm     = $realServiceLocator->get('FormElementManager')->get('CSAdmin\Form\LoginForm');

        return new LoginController(
            $loginService,
            $loginForm
        );
    }
}

/module/CSAdmin/src/CSAdmin/Factory/AdminControllerFactory.php:

namespace CSAdmin\Factory;

use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use CSAdmin\Controller\AdminController;
use Zend\View\Helper\BasePath;

class AdminControllerFactory implements FactoryInterface
{
    /**
    * Create service
    *
    * @param ServiceLocatorInterface $serviceLocator
    * @return mixed
    */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {

        $realServiceLocator = $serviceLocator->getServiceLocator();
        //$viewHelper        = $realServiceLocator->get('Zend\View\Helper\BasePath');
        //return new AdminController($viewHelper);
        return new AdminController();
    }
}

/module/CSAdmin/src/CSAdmin/Factory/LoginControllerFactory.php:

namespace CSAdmin\Factory;

use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use CSAdmin\Controller\LoginController;

class LoginControllerFactory implements FactoryInterface
{
    /**
    * Create service
    *
    * @param ServiceLocatorInterface $serviceLocator
    * @return mixed
    */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {

        $realServiceLocator = $serviceLocator->getServiceLocator();
        $loginService        = $realServiceLocator->get('CSAdmin\Service\LoginServiceInterface');
        $loginForm     = $realServiceLocator->get('FormElementManager')->get('CSAdmin\Form\LoginForm');

        return new LoginController(
            $loginService,
            $loginForm
        );
    }
}

EDIT #5:

After correcting the type of quotes being used I am still not getting the stylesheets in my layout. As a test I change ->appendStylesheet() to ->someMethod() and it properly reports that the method does not exist. So it definitely has an instance of the HeadLink object. As a next step I decided to just try defining everything in the layout file and it still does not use the stylesheets. See below for the exact code used in the <head> tag of my layout file.

<?php echo $this->doctype(); ?>
<html lang="en">
<head>      
    <meta charset="utf-8">
    <title><?php echo $this->layout['title']; ?></title> //Intend to change eventually.
<?php 
$this->headLink()->appendStylesheet('/css/admin/form.css');
$this->headLink()->appendStylesheet('/css/admin/styles.css');
echo $this->headScript();
echo $this->headStyle(); //This outputs nothing when viewing with the chrome debugger.
</head>

EDIT #6: In order to get it to work, instead of using:

echo $this->headScript();
echo $this->headStyle();

I just had to do:

echo $this->headLink();
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • drjgk44268 2015-11-18 18:00
    已采纳

    You will have to add echo to output the result...

    echo $this->headScript();
    echo $this->headStyle();
    echo $this->headLink();
    

    UPDATE

    To get the Zend\View\HelperPluginManager in your controller you can do like this:

    $viewHelperManager = $this->getServiceLocator()->get('ViewHelperManager');
    

    Then you can do:

    $headLinkHelper = $viewHelperManager->get('headLink');
    

    UPDATE 2

    Another thing, but it is a bit ridiculous, no wonder it was hard to find. You used wrong quotes:

    `ViewHelperManager` //You cannot use these: `
    

    Try like this:

    'ViewHelperManager'
    

    or like this:

    "ViewHelperManager"
    
    已采纳该答案
    打赏 评论
  • douweibiao8471 2015-11-18 17:55

    you need to append file in this way

    $this->headScript()->appendFile(
         '/js/prototype.js',
         'text/javascript',
            array('conditional' => 'lt IE 7')
        );
    

    then you write it

            echo $this->headScript();
    

    note echo head script is required only one time. otherwise you inser js more time

    more info at

    http://framework.zend.com/manual/current/en/modules/zend.view.helpers.head-script.html

    打赏 评论

相关推荐 更多相似问题