I have a custom module that uses AJAX. Everything works fine the way it is. I'm just wondering if it's the proper way to do it in Drupal. I'm new to Drupal 8 and 9 programming

This is a line from my code

$link ='<a href="/nojs/my-link/1" class="use-ajax btn btn-default">Test AJAX</a>';

Is this ok to do or should I be building my link? If so, why and how?

EDIT

I currently build non-ajax links like

  $url = Url::fromRoute('entity.node.canonical', array('node' => $record->nid));
  $title_link = Link::fromTextAndUrl($record->title, $url);
  $title_link =$title_link->toRenderable();
  $title_link=render($title_link);
有帮助吗?

解决方案

If you just need to add the classes I believe it can be done like so

$url = Url::fromRoute(
  'entity.node.canonical', 
  ['node' => $record->nid], 
  ['#attributes' => ['class' => ['btn', 'btn-default', 'use-ajax']]]
);

 $title_link = Link::fromTextAndUrl($record->title, $url);

At that point $title_link should be able to be rendered in the template as is!

// php
$variables['title_link'] = $title_link;

// twig
{{ title_link }}
许可以下: CC-BY-SA归因
scroll top