'Load css/js once on included (or embeded) file instead of parent

I try to make my symfony application more component-based. I've managed to achieve this by putting reusable sections in separate files and include or embed them in the files I want. Now one issue I have is that I have to load css and js related to these components in the files that includes or embeds them. It would be really nice if I could load css and js inside these components so that anyone who would like to use them can just include or embed them and does not have to search which css-js files are related and load them as well.

For example if i load card.js inside card.html.twig file on page1 it will console jscode twice which is unwanted.

card.js

console.log('jscode');

base.html.twig

<!DOCTYPE html>
<html>
  <head>
    .
    .
    .
    <link rel="stylesheet" href="/css/global.css">
    {% block page_css %}{% endblock %}
    <script type="text/javascript" src="/js/flatpickr.js"></script>
    {% block page_js %}{% endblock %}
  </head>
  <body>
    <main>
       {% block body %}{% endblock %}
    </main>
  </body>
</html>

page1.html.twig

{% extends 'base.html.twig' %}
{% block page_css %}
  <link rel="stylesheet" href="/components/card/card.css">
{% endblock %}
{% block page_js %}
  <script type="text/javascript" src="/components/card/card.js"></script>
{% endblock %}
{% block body %}
  <section>
  .
  .
  .
  </section>
  {% embed 'components/card/card.html.twig' 
    with {
      'color': 'red',
      'message': 'some message here'
    } 
  %}
    {% block componentChildren %}
      {{ form_widget(form.title) }}
      {{ form_widget(edit_form.workingHours, {'attr': {'class': 'hours_combined'}}) }}
    {% endblock %}
  {% endembed %}
  {% embed 'components/card/card.html.twig' 
    with {
      'color': 'red',
      'message': 'some message here'
    } 
   %}
     {% block componentChildren %}
       {{ form_widget(form.title) }}
     {% endblock %}
   {% endembed %}
{% endblock %}

page2.html.twig

{% extends 'base.html.twig' %}
{% block page_css %}
  <link rel="stylesheet" href="/components/card/card.css">
{% endblock %}
{% block page_js %}
  <script type="text/javascript" src="/components/card/card.js"></script>
{% endblock %}
{% block body %}
  {% embed 'components/card/card.html.twig' 
    with {
      'color': 'red',
      'message': 'some message here'
    } 
  %}
    {% block componentChildren %}
      {{ form_widget(form.title) }}
    {% endblock %}
  {% endembed %}
  <section>
  .
  .
  .
  </section>

card.html.twig

{# 
how to load card.css and card.js here without loading them multiple times if this
component is embedded multiple times in the same page? 
#}
<div class="card">
  <h3 style={{color}}>{{message}}</h3>
  .
  .
  .
  {% block componentChildren %}{% endblock %}
</div>


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source