Improve linking to md version of an entity

Created on 28 April 2025, 1 day ago

Problem/Motivation

How could would be it if a developer could just do $entity->url('canonical-md') in code to link to the Markdown version of an entity.

Steps to reproduce

Proposed resolution

Considering what happens in \Drupal\Core\Entity\EntityBase::toUrl(), alternating the link templates of entities should do the job.

Remaining tasks

User interface changes

API changes

Data model changes

Feature request
Status

Active

Version

1.0

Component

Code

Created by

🇭🇺Hungary mxr576 Hungary

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

  • Issue created by @mxr576
  • 🇭🇺Hungary mxr576 Hungary
  • 🇭🇺Hungary mxr576 Hungary
  • 🇨🇴Colombia i'mbatman

    Thanks for the great suggestion, mxr576! I already have this implemented in a local branch of the module, though I haven’t been able to push it yet.

    @Christophweber, what mxr576 is suggesting is essentially adding a new Link Template to entities marked as supported for Markdown conversion.

    Here’s the official documentation on how to do it: Link Relation Types and Link Templates

    The implementation is straightforward and looks like this:

    /**
     * Implements hook_entity_type_alter().
     *
     * Adds a 'markdownify' link template to supported entity types.
     */
    function markdownify_entity_type_alter(array &$entity_types): void {
      /** @var \Drupal\Core\Entity\EntityTypeInterface[] $entity_types */
      $validator = \Drupal::service('markdownify.supported_entity_types.validator');
    
      foreach ($validator->getSupportedEntityTypes() as $entity_type_id) {
        if (!isset($entity_types[$entity_type_id])) {
          continue;
        }
    
        $entity_type = $entity_types[$entity_type_id];
        if (!$entity_type instanceof EntityTypeInterface) {
          continue;
        }
    
        // Add 'markdownify' link template based on the canonical path.
        if ($entity_type->hasLinkTemplate('canonical')) {
          $canonical_path = $entity_type->getLinkTemplate('canonical');
          $entity_type->setLinkTemplate('markdownify', $canonical_path . '.md');
        }
      }
    }
    

    The reason I haven’t pushed this contribution yet is that I’m uncertain about the name of the link template. In my implementation, I named it 'markdownify', so people can get the Markdown URL using code like this:

    $markdown_url = $entity->toUrl('markdownify')->setAbsolute(TRUE)->toString();
    

    However, in mxr576's example, the name is 'canonical-md', which means the URL would be retrieved like this:

    $markdown_url = $entity->toUrl('canonical-md')->setAbsolute(TRUE)->toString();
    

    Do you have any preferences for the naming convention? Let me know, and I’ll push a merge request with the changes.

    Thanks!

Production build 0.71.5 2024