2

I'm using Drupal 8.1.10. I have a basic page with the URL alias "/enter-competition". On a twig template (not associated with that page), I have the following HTML:

<a href="/enter-competition">Enter Competition</a>

I need this link to only be included if that basic page is in a published state, like so:

{% if page_is_published %}
<a href="/enter-competition">Enter Competition</a>
{% endif %}

How can I check if that basic page is published/unpublished?

1 Answer 1

4

If you look in the core theme file core/themes/stable/templates/content/node.html.twig under "Available variables:" you'll find

node.isPublished() will return whether the node is published or not.

Can also be found here.

Which means you can do:

{% if node.isPublished() %}
  {# content for published nodes #}
{% endif %}

Edit by OP: (17/08/2017)

The above was a partial answer, but I also had the problem that the twig file I needed do this check in wasn't associated with the node I needed to check the published state of. So, using something like menu_get_object wouldn't work.

Since Drupal doesn't seem to have any easy function to get a node by ID/Alias, I created the following function to get a node by URL alias:

public static function getPublishedStateByPageAlias($pageAlias)
{
  $nodeIsPublished = false;

  // Get node path from alias
  $path = \Drupal::service('path.alias_manager')->getPathByAlias($pageAlias);

  // If there is a valid path
  if(preg_match('/node\/(\d+)/', $path, $matches)) {
    // Get the node from the path
    $node = \Drupal\node\Entity\Node::load($matches[1]);
    // Start an entity manager
    $node_storage = \Drupal::entityManager()->getStorage('node');
    // Get the relevant node by its ID using the entity manager
    $chosenNode = $node_storage->load($node->id());

    // Is it published?
    $nodeIsPublished = $chosenNode->isPublished();
  }

  return $nodeIsPublished;
}

I could then call this function in my site's custom module, pass the result to the relevant twig file as a boolean variable, and conduct the necessary check.

2
  • Okay, that's a start. However, I need to do this check in a twig file which is being included in all nodes, and the check needs to be for just one specific node (not necessarily the one being viewed at the time). Is it possible to check if a specific node (e.g. 1017) is published without viewing that particular node? Aug 17, 2017 at 10:12
  • Okay, I've extended @enzipher's answer to include the additional steps I took to solve the problem. Not sure if this is the best DrupalSE etiquette, but hopefully that's cool. Aug 17, 2017 at 15:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.