Manuel:LinkRenderer.php

This page is a translated version of the page Manual:LinkRenderer.php and the translation is 9% complete.
Version de MediaWiki :
1.28
Gerrit change 284750

MediaWiki\Linker\LinkRenderer is a class to create HTML links for a specific title. It was refactored out of the Linker class in MediaWiki 1.28.

Obtenir une instance LinkRenderer

In general, the easiest way to get a LinkRenderer instance is from MediaWikiServices:

use MediaWiki\MediaWikiServices;
$linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();

This will provide you with an instance prepared for the current user (RequestContext::getMain()->getUser()).

Some contexts will have their own LinkRenderer instance, like the Parser or SpecialPages :

// in a parser function
$linkRenderer = $parser->getLinkRenderer();
// in a special page
$linkRenderer = $this->getLinkRenderer();

If you need to set custom options (see below), you can create your own! You shouldn't modify the main instances since that will affect the entire request state.

// Get a LinkRendererFactory first
$factory = MediaWikiServices::getInstance()->getLinkRendererFactory();
$linkRenderer = $factory->create();
// or
$linkRenderer = $factory->createForUser( $user );
// Set options (for example)
$linkRenderer->setStubThreshold( 15 );

Okay, you now have a LinkRenderer instance. Let's make some links! At the very minimum you'll need a Title or TitleValue target to link to. The examples below all use TitleValue for simplicity, but the equivalent Title object can be used as well.

$link = $linkRenderer->makeLink( new TitleValue( NS_MAIN, 'Main_Page' ) );

Will give you:

<a href="/wiki/Main_Page" title="Main Page">Main Page</a>

If you want to change the link text:

$link = $linkRenderer->makeLink( new TitleValue( NS_MAIN, 'Main_Page' ), 'not main page' );
<a href="/wiki/Main_Page" title="Main Page">not main page</a>

This text will automatically be escaped (different from its Linker predecessor). If you need to include HTML, you can armor the content:

$link = $linkRenderer->makeLink( new TitleValue( NS_MAIN, 'Main_Page' ), new HtmlArmor( '<b>Stuff</b>' ) );
<a href="/wiki/Main_Page" title="Main Page"><b>Stuff</b></a>

Options

LinkRenderer has a few options that are set per-instance and can be customized:

  • ForceArticlePath (setForceArticlePath()/getForceArticlePath()) - Forces the link to use the article path (see $wgArticlePath ) even if a query string is present, resulting in URLs like /wiki/Main_Page?action=foobar.
  • ExpandURLs (setExpandURLs()/getExpandURLs()) - Controls whether the URL should be expanded, and can be set to any of the PROTO_* constants.
1.39
Gerrit change 780751
  • StubThreshold (setStubThreshold()/getStubThreshold()) - Threshold at which articles should be marked with the stub CSS class. Using LinkRendererFactory::createFromUser() will automatically set this.