Drupal - How to load the node to print the node title, etc?
$node = \Drupal\node\Entity\Node::load($id)
or
$nodes = \Drupal\node\Entity\Node::loadMultiple(array $ids = NULL)
$node->getTitle();
One way is to get the title and body of your content type by using views. Create a 'news' view of content type news and select fields - title and body.
Now in your current theme's template folder, create a file :
views-view-table--news--block.html.twig
There you can fetch title and body field and style as you want:
{% set i = 1 %}
<div id="tabs">
<ul>
{% for key,row in rows %}
<li><a href="#tab-{{key+1}}">
{% for column in row %}
{{ column.field_display_date_1 }} </a></li>
{% endfor %}
{% endfor %}
</ul>
Also you can use below query in your custom module if you don't want to use views module. It will load node object of content type 'news':
$nids = \Drupal::entityQuery('node')
->condition('type', $content_type, '=')
->condition('langcode', $language, '=')
->condition('status', 1, '=')
->execute();
$nodes = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($nids);
foreach ($nodes as $key => $value) {
$title = $value->title->value;
$description = strip_tags($value->body->value);
}
When you are in a node template like node--news.html.twig
, then the node is already loaded in the variable node
and you can access the field values in twig:
{{ node.field_myfield.value }}
You get the raw values from the database. They are escaped by twig, to prevent hacks. But this escaping makes them useless for any html formatted content.
Most times you use the field values from node for logic, like checking a boolean.
If you want to display the fields, it is preferable to use content
:
{{ content.field_myfield }}
The node title is preloaded in the variable label
:
{{ label }}