5.7 - How to pass values from view.php to on_page_view()

Permalink
I am building a free block for 5.7 that displays icons on a page. It doesn't add an image to the page, instead it uses a CSS class with a background image. To make the block output support Internet Explorer 8, I had to anticipate all use combinations. This meant creating a huge number of CSS classes. The view.css is large even after minifying, but drops down to under 15k with gzip.

The block works and is useful, but I don't want to discourage people from using it if they don't have gzip enabled on their server.

If I can generate CSS classes and styles and inject them into the page head. This would allow me to make only the classes and styles I need and keep file sizes at a minimum.


Goal:
- build CSS classes and styles from user input
- inject those CSS classes and styles into the page head using a <style> tag

one approach using the on_page_view() and addHeaderItem() methods

Example:
- the CSS classes and styles are built in view.php, then wrapped in a style tag and set to a variable $iconStyles

- the idea is that $iconStyles is passed to the on_page_view() method
- in on_page_view(), addHeaderItem() adds the value of $iconStyles (a string) to the page head

in the block controller:
public function on_page_view()
{
    $this->addHeaderItem($iconStyles);
}

To test to see if this approach worked, I set values and variables in on_page_view() directly. This worked - a style tag was added to the page head.
public function on_page_view()
{
    $style = '<style>.icon-container-wrapper{background:green;}</style>';
    $this->addHeaderItem($style);
}

Question:
- I am currently building the CSS classes and styles and setting them to variables in view.php.
- What is a recommended approach to take the variables and values created in view.php and pass them to the on_page_view() method?


The following was my first crack at it. I imagine this didn't work for many reasons.

I was thinking of something like this to use as a setter.
protected $iconStyles = '';
public function setIconStyles($iconStyles)
{
    $this->iconStyles = $iconStyles;
}

In my view.php, I would use something like this. Using $controller was only a guess.
$controller->setIconStyles($iconStyles);

Thank you

MrKDilkington
View Replies:
MrKDilkington replied on at Permalink Reply
MrKDilkington
I believe I found the proper way to do this now.

I now see where I was making mistakes.
- $controller is the object to use to access the controller
- in setIconStyles(), I forgot to return $iconStyles

Test Example

in view.php:
$iconStyles = '<style>.icon-container{border:10px solid red;}</style>';
$controller->setIconStyles($iconStyles);

in the block controller:
protected $iconStyles = '';
public function setIconStyles($iconStyles)
{
    $this->iconStyles = $iconStyles;
    return $iconStyles;
}
public function on_page_view()
{
    $this->addHeaderItem($this->iconStyles);
}