craftcms / cms

Build bespoke content experiences with Craft.
https://craftcms.com
Other
3.22k stars 627 forks source link

FR: Add ability to pass in attributes to getLink #4543

Closed rungta closed 4 years ago

rungta commented 5 years ago

Description

It would be quite handy to pass in attributes (especially classes) to the getLink() function on craft\base\Element, similar to the newly introduced attr() Twig function.

{# This #}
<a class="bg-red" href="{{ entry.url }}">{{ entry.title }}</a>

{# Becomes #}
{{ entry.getLink({ class: 'bg-red' }) }}
brandonkelly commented 5 years ago

getLink() is defined by ElementInterface so adding an $attr argument would be a breaking change for element types, so we’ll have to wait until Craft 4 to implement this, unfortunately.

rungta commented 5 years ago

Ah okay. Now we wait.

fvaldes33 commented 5 years ago

@rungta - you could always create a behavior to handle that functionality.

use yii\base\Behavior;
use craft\helpers\Template as TemplateHelper;
use craft\helpers\Html;

class BaseEntryBehavior extends Behavior
{
    public function getLinkEl($attrs = [])
    {
        $entry = $this->owner;

        $attrs['href'] = $entry->getUrl();

        return TemplateHelper::raw(Html::tag('a', $entry->title, $attrs));
    }
}

In twig:

{{ entry.getLinkEl({ class: 'button' }) }}
rungta commented 5 years ago

Great suggestion @fvaldes33. Thanks!

piotrpog commented 4 years ago

@brandonkelly Maybe just create a new method and call it linkTag or something like that?

brandonkelly commented 4 years ago

Actually this isn’t really needed anymore as of Craft 3.3, thanks to the |attr Twig filter.