5 use Drupal\Core\Render\RenderableInterface;
6 use Drupal\Core\Routing\LinkGeneratorTrait;
9 * Defines an object that holds information about a link.
11 class Link implements RenderableInterface {
14 * @deprecated in Drupal 8.0.x-dev, will be removed before Drupal 9.0.0.
16 use LinkGeneratorTrait;
19 * The text of the link.
26 * The URL of the link.
28 * @var \Drupal\Core\Url
33 * Constructs a new Link object.
36 * The text of the link.
37 * @param \Drupal\Core\Url $url
40 public function __construct($text, Url $url) {
46 * Creates a Link object from a given route name and parameters.
49 * The text of the link.
50 * @param string $route_name
51 * The name of the route
52 * @param array $route_parameters
53 * (optional) An associative array of parameter names and values.
54 * @param array $options
55 * The options parameter takes exactly the same structure.
56 * See \Drupal\Core\Url::fromUri() for details.
60 public static function createFromRoute($text, $route_name, $route_parameters = [], $options = []) {
61 return new static($text, new Url($route_name, $route_parameters, $options));
65 * Creates a Link object from a given Url object.
68 * The text of the link.
69 * @param \Drupal\Core\Url $url
70 * The Url to create the link for.
74 public static function fromTextAndUrl($text, Url $url) {
75 return new static($text, $url);
79 * Returns the text of the link.
83 public function getText() {
88 * Sets the new text of the link.
95 public function setText($text) {
101 * Returns the URL of the link.
103 * @return \Drupal\Core\Url
105 public function getUrl() {
110 * Sets the URL of this link.
113 * The URL object to set
117 public function setUrl(Url $url) {
123 * Generates the HTML for this Link object.
125 * Do not use this method to render a link in an HTML context. In an HTML
126 * context, self::toRenderable() should be used so that render cache
127 * information is maintained. However, there might be use cases such as tests
128 * and non-HTML contexts where calling this method directly makes sense.
130 * @return \Drupal\Core\GeneratedLink
131 * The link HTML markup.
133 * @see \Drupal\Core\Link::toRenderable()
135 public function toString() {
136 return $this->getLinkGenerator()->generateFromLink($this);
142 public function toRenderable() {
145 '#url' => $this->url,
146 '#title' => $this->text,