Hi everyone,
I'm trying override the default behavior of adding rel="nofollow" to the links of a post reply, but only if they point to my main website. As an example, if I refer here to Flarum website, it would be better if the search engines could keep crawling it.
I'm trying to do this task in several different ways, but without any success. I had two promising solutions in mind, but couldn't make any of them work. I'm summarizing them to see if anyone has a suggestion on how to proceed from there or if it there's any example I can follow.
1) Trying to use the Flarum\Formatter\Event\Configuring
event:
// extend.php
return [
function (Dispatcher $events, Container $container) {
$events->listen(Flarum\Formatter\Event\Configuring::class, MyProject\SetupFormatter::class);
}
];
// on SetupFormatter I had something like this on my handle:
$event->configurator->templateNormalizer->append(
function (DOMElement $template) {
foreach ($template->getElementsByTagName('a') as $a) {
$a->getAttribute('href');
}
}
);
The problem here was that only the templates for the urls were being parsed (something like {Discussion}/{id}
) and probably related to the page building, not the posts. Mainly because to make this code being accessed, I had to clear Flarum cache. So I tried the second solution.
2) Extend the Flarum\Formatter\Formatter
class and setup as the main parser for Flarum\Post\CommentPost
:
// extend.php
...
function (Dispatcher $events, Application $app) {
$formatter = new MyProjectFormatter(
new Repository($app->make('cache.filestore')),
$app->make('events'),
$app->storagePath() . '/formatter'
);
FormatterDispatcher::setFormatter($formatter);
$events->listen(Flarum\Event\ConfigurePostTypes::class, FormatterDispatcher::class);
},
...
// MyProjectFormatter
class MyProjectFormatter extends Formatter
{
// this is the function defined on Flarum\Formatter\Formatter
// I thought if I could override this, I could set the configuration I want for my links, but
// the debugger isn't stopping here when I post a comment. I asserted if PostComment was using MyProjectFormatter, and it was correct
protected function configureExternalLinks(Configurator $configurator)
{
$dom = $configurator->tags['URL']->template->asDOM();
foreach ($dom->getElementsByTagName('a') as $a) {
$rel = $a->getAttribute('rel');
$a->setAttribute('rel', "$rel nofollow ugc");
}
$dom->saveChanges();
}
}
Debugging, I checked that the setContentAttribute
from Flarum\Post\CommentPost
was receiving the expected formatter (MyProjectFormatted), but the function above was not being called.
So anyone have any idea on how can I proceed to make it work?