Zend Framework 2 - How to include partial from library
Asked Answered
W

1

7

I wrote a partial which I want to use in several modules. I thought the best way would be to put it into my custom library.

But unfortunately I couldn't figure out a way to include this partial without using a very ugly path like:

echo $this->partial('/../../../../vendor/myvendor/library/MyVendor/View/Views/FormPartial.phtml'
, array(...));

Any ideas how to link to my vendor directory from my view?

Whiles answered 21/12, 2012 at 13:46 Comment(1)
Have you tried the addBasePath()? I think you can use it to add a path where your view script will be looked for ... so you should be able to use the view without such a long path again and againAccordant
M
14

The problem is the resolver can't resolve the path of the view template you had provided. I usually add a configuration entry for all accessible partials in the template_map entry in the module.config.php

for example I have header and footer partials like this my view/layout/header.phtml and view/layout/footer.phtml

below is my config

'template_map' => array(
    'layout/layout'         => __DIR__ . '/../view/layout/layout.phtml',
    'header'                => __DIR__ . '/../view/layout/header.phtml',
    'footer'                => __DIR__ . '/../view/layout/footer.phtml',
    'error/404'             => __DIR__ . '/../view/error/404.phtml',
    'error/index'           => __DIR__ . '/../view/error/index.phtml',
),

and inside my layout view script I simply put

<?php echo $this->partial('header'); ?>

and

<?php echo $this->partial('footer'); ?>

Another if you have your partials under /module/controller/action format you can also do

<?php echo $this->partial('/module/controller/action'); ?>

you should place the view script in the view folder of your module's controller folder

Mcintire answered 22/12, 2012 at 14:27 Comment(2)
Thanks for this detailed answer. but IS there a way to put the partial in a central place where several modules can access it?Seften
In zf2 any partial defined in config or in any module is equally accessible in any modules as defined above. If you want to have it in a central place the best place would be your application view folder. place all your partials under partialfoldername/yourpartial.phtml then you can access your partial as defined by method 2 as '/application/partialfoldername/yourpartial' Note: choose the partialfoldername such that it doesn't match with your any defined controllersMcintire

© 2022 - 2024 — McMap. All rights reserved.