@AkiShankar's answer works, but creates a lot of work for the developer in the twig template. If you work directly off of the entity and do getFieldCollectionItem(), you are forced to validate the data within your twig, and you can't use field formatters, so for something like a google map, pulling the data directly out without a formatter doesn't work so well. If you want to be able to use view modes in your field collection (this works for paragraphs and entity references as well), you can create a custom field formatter for your entity that renders the fields. You can then access the child fields easily in the parent twig:
At /modules/custom/mymodule/src/Plugin/Field/FieldFormatter/EntityComponentFormatter.php
namespace Drupal\mymodule\Plugin\Field\FieldFormatter;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\Plugin\Field\FieldFormatter\EntityReferenceEntityFormatter;
/**
* Plugin implementation of the 'entity reference rendered entity' formatter.
*
* @FieldFormatter(
* id = "entity_component_formatter",
* label = @Translation("Rendered entity variables (available to parent template)"),
* description = @Translation("Entity with fields available in parent template."),
* field_types = {
* "entity_reference"
* }
* )
*/
class EntityComponentFormatter extends EntityReferenceEntityFormatter {
/**
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = parent::viewElements($items, $langcode);
foreach ($this->getEntitiesToView($items, $langcode) as $delta => $entity) {
$view_builder = $this->entityTypeManager->getViewBuilder($entity->getEntityTypeId());
$elements[$delta] = $view_builder->build($elements[$delta]);
}
return $elements;
}
}
You can iterate through in your twig like this:
{% for key, item in content.field_my_field_collection %}
{{ item.field_1 }}
{{ item.field_2 }}
{% endfor %}
If you don't want to create a custom formatter, you can do the same thing in hook_entity_view:
/**
* Implements hook_entity_view().
*
* Gets the output for extra fields.
*/
function mymodule_entity_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {
if ($entity->getEntityType()->id() == 'node' && $entity->bundle() == 'article' && $view_mode == 'myviewmode' && !empty($build['field_my_field_collection'])) {
$view_builder = \Drupal::entityTypeManager()
->getViewBuilder('field_collection_item');
$build['field_my_field_collection'] = $view_builder->build($build['field_my_field_collection']);
}
}