Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Passing helper php function to pug context ? #95

Closed
mcoenca opened this issue Dec 2, 2016 · 2 comments
Closed

Passing helper php function to pug context ? #95

mcoenca opened this issue Dec 2, 2016 · 2 comments
Labels

Comments

@mcoenca
Copy link
Contributor

mcoenca commented Dec 2, 2016

(Not sure if it's not possible or if I have not found the right way to do it ?? I am not very experienced in php scopes sorry if this is a stupid question...)

I would like to be able to pass a php function to pug at render time, to be able to call it directly in my template. Without resorting to a global function.

That way I would be able to use the same helper function name in all my template, even if its behaviour is dependent of the route context.

Something like:

// in HomeController.php

public function get() {
    function pathFor($pathName) use ($this) {
        return $this->router->pathFor($pathName);
    }

   return $this->pug->render('productPage.pug', $this->templateParams, [pathFor?] )
}
//- in productPage.pug

p
    #[a href=pathFor('/home')) Click here quick quick quick QUICK !]

would get me

<a href="/amazing-product-you-will-like-and-buy-home-page"> Click here quick quick quick QUICK ! </a>

Thanks for your help !
Btw: Amazing package 💯

@kylekatarnls
Copy link
Member

Hi,

The easiest in your case would probably be a closure:

public function get() {
    $routerPathFor = array($this->router, 'pathFor');
    $pathFor = function ($pathName) use ($routerPathFor) {
        return call_user_func($routerPathFor, $pathName);
    };
    // Depending on your PHP version you can use directly $routerPathFor

   return $this->pug->render('productPage.pug', $this->templateParams, array(
      'pathFor' => $pathFor
   ));
}

You can also use share to get the function available in any template:

// somewhere in a global place after $this->pug is instanciated
// for example, the constructor of an abstract class that all controllers extend
$this->pug->share('pathFor', $pathFor);

With such a template:

a(href=$pathFor('foo'))=$pathFor('bar')

I hope it solve your problem.

@mcoenca
Copy link
Contributor Author

mcoenca commented Dec 2, 2016

Perfect ! Well that means I need to dive in php closures a bit deeper...

Thanks for your very fast answer 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants