So I started building this plugin to add a twig extension to escape but leave
intact. For some reason when I try install it or use it without the force argument on the import command in the plugin file set to true it does not work. If i set it to true, though, it installs fine and works fine.
My plugin Directory Structure:
craft
- plugins
- nbsp
NbspPlugin.php
- twigextensions
NbspTwigExtension.php
Here is my NbspPlugin.php file:
<?php
namespace craft;
class NbspPlugin extends BasePlugin {
function getName()
{
return Craft::t('  Twig Filter');
}
function getVersion()
{
return '1.0';
}
function getDeveloper()
{
return 'Rick';
}
function getDeveloperUrl()
{
return '';
}
public function addTwigExtension()
{
Craft::import('plugins.nbsp.twigextensions.NbspTwigExtension');
return new NbspTwigExtension();
}
}
Here is my NbspTwigExtension.php file:
<?php
namespace Craft;
class NbspTwigExtension extends \Twig_Extension
{
public function getName()
{
return ' filter';
}
public function getFilters()
{
$returnArray = array();
$methods = array(
'escapeNonNbsp',
);
foreach ($methods as $methodName) {
$returnArray[$methodName] = new \Twig_Filter_Method($this, $methodName, ['pre_escape' => 'html', 'is_safe' => array('html')]);
}
return $returnArray;
}
public function escapeNonNbsp($content)
{
// perform filter operations
return str_replace('&nbsp;', ' ', $content);
}
}
I cannot install the plugin. I get an exception
Can't find Craft\NbspTwigExtension
referencing the return line of the addTwigExtension()
Method. If I add the force = true
argument to the import above it, it installs it, but then upon attempting to use the filter in the twig template it fails even with the import being forced.
What am I doing wrong?
EDIT - I found one bug in my set up where the name of my method in the extension class needs to match how I call the filter from twig. I changed it to:
<?php
namespace Craft;
class NbspTwigExtension extends \Twig_Extension
{
public function getName()
{
return ' filter';
}
public function getFilters()
{
$returnArray = array();
$methods = array(
'nbsp',
);
foreach ($methods as $methodName) {
$returnArray[$methodName] = new \Twig_Filter_Method($this, $methodName, ['pre_escape' => 'html', 'is_safe' => array('html')]);
}
return $returnArray;
}
public function nbsp($content)
{
// perform filter operations
return str_replace('&nbsp;', ' ', $content);
}
}
However it still requires "force" true on the import command to work or install. Why!!?
NbspPlugin
class hasnamespace craft
, when it should benamespace Craft
. Fix that and see if it helps.