getherbert / herbert

The WordPress Plugin Framework:
http://getherbert.com/
631 stars 94 forks source link

Bug access to the Helper class from Twig #64

Open terrylau2013 opened 9 years ago

terrylau2013 commented 9 years ago

In api.php has a function allows the use of {{ Socializr.helper() }} to use any public method from the Helper Class. But, this function pass non-Ascii forward slash ('/') to Helper class.

Code in Twig {{ Socializr.helper('assetUrl', 'semantic.min.css') }}

Output http://localhost/wordpress/wp-content/plugins/MyPlugin/resources/assets//semantic.min.css

terrylau2013 commented 9 years ago

{{ Socializr.helper('assetUrl', 'semantic.min.css') }} << this code not work on route twig?

ConnorVG commented 9 years ago

Hey @terrylau2013, can I just confirm you have this setup as it is expected? In order for this to work, at-least three files must be setup. The herbert.config.php, app/api.php and any .twig files.

Your herbert.config.php must define the API to make Herbert aware of it's existance:

<?php

return [
    // ... other stuff

    /**
     * The APIs to auto-load.
     */
    'apis' => [
        'MyPlugin' => __DIR__ . '/app/api.php'
    ],

    // ... other stuff
];

Your app/api.php file must add the helper function to the api:

<?php namespace MyPlugin;

/** @var \Herbert\Framework\API $api */

/**
 * Gives you access to the Helper class from Twig
 * {{ MyPlugin.helper('assetUrl', 'icon.png') }}
 */
$api->add('helper', function ()
{
    $args = func_get_args();
    $method = array_shift($args);

    return forward_static_call_array(__NAMESPACE__ . '\\Helper::' . $method, $args);
});

Your .twig file must correctly reference this API via it's name.

{{ MyPlugin.helper('assetUrl', 'semantic.min.css') }}

Have you got it setup as shown here?

One thing to note is that if you request a view to be rendered before Herbert has fully booted, this API may not be available. IE: If you try to render something in a file defined in the requires section, it will not have access to any API defined in the app/api.php file. The best way to avoid this is to use hooks. Such as the plugins_loaded hook.

terrylau2013 commented 9 years ago

@ConnorVG, Thanks you. You are right. I have some render method in requires section so I can't access to any api.

giwrgos88 commented 8 years ago

I tried this method and not working. if i do

dd()

my api is null. any help @terrylau2013 @ConnorVG? here is my post