0

I have a specific block of code which is a newsletter subscription form with a script. I have to use this code on multiple templates.

Currently I am using it on these two templates

  • app\design\frontend\base\default\template\fekete\Newsletter2Go\customer\form\newsletter.phtml

  • app\design\frontend\base\default\template\fekete\Newsletter2Go\subscribe.phtml

-

<!-- Partial A -->
<form id="subscribe" ...>
    <input ...>
</form>
<script>
  ...
</script>

Of course I could just copy & paste this code to all needed templates. But the maintenance effort would be extremly high if I would have to edit the code, because I would need to edit it in all templates.

Is there a way to save that code block and use it in multiple templates?

  • I think there is one way, you can add your form structure in one static block and then use that static block in multiple phtml files. – Raj Aug 2 '18 at 8:33
  • @Raj, Thank you for your input. Do I have to create that static block in the backend via CMS or in my module? I need to ship the endproduct as module – Black Aug 2 '18 at 8:36
  • 1
    You have to create static block using CMS and then call that static block in your phtml file like this: <?php echo $this->getLayout()->createBlock('cms/block')->setBlockId('block_identifier')->toHtml(); ?> – Raj Aug 2 '18 at 8:45
1

Create a phtml file with your code and insert it in the following way:

$block = $this->getLayout()
  ->createBlock('core/template')
  ->setTemplate('path/to/your.phtml');

echo $block->toHtml();
  • forgot to mention: the path should be under template folder. something like 'callouts/test.phtml' in case it is stored in following location app/design/frontend/base/default/template/callouts/test.phtml – Moshe Shperling Aug 2 '18 at 9:32
  • This works, but as soon as I try to call php variables from the template where I include the partial (code block) then it does not work anymore. – Black Aug 2 '18 at 10:26
  • What kind of variables are you trying to call? – Moshe Shperling Aug 2 '18 at 10:56
  • Variables which I have defined in the template where I include the partial. At the moment helpers and the customer object. I have to initialize these variables again in the partial to make it work, but this is not a good solution. – Black Aug 2 '18 at 11:20
  • 1
    When you are in the phtml context you can access only the variables that are in block type class. In the code i sent you the type is core/template therefore you can access only default attributes that defined in core_template class. You can solve it by defining your own custom module and giving the block type of your module block class file. There you can do anything. – Moshe Shperling Aug 2 '18 at 11:26

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.