How do I move conditional library includes out of a twig template? I have a javascript library with several separate files which I would like to include only if necessary. I currently determine which need to be included within the twig template. 

{{ attach_library('flot_d8/flot') }}
{% if options['xaxis']['mode'] == 'categories' %}
{{ attach_library('flot_d8/categories') }}
{% endif %}

{% if options['selection'] is defined %}
{{ attach_library('flot_d8/selection') }}
{% endif %}

{% if options['pan'] is defined %}
{{ attach_library('flot_d8/navigate') }}
{% endif %}

{% if resizable == true %}
{{ attach_library('flot_d8/resize') }}
{% endif %}

{% if nodiv == false %}
&lt;div id="{{div_id}}" style="width:600px;height:300px;"&gt;&lt;/div&gt;
{% endif %}


Is there a better, or alternative way to perform this logic? I would like to override this template in another module and make the simple &lt;div&gt; element more complex. However, I would have to copy all the library inclusion logic with it.
Attaching libraries in Drupal 8 should be done by either attaching the #attached attribute to render arrays or by adding them to the info file to be added to all pages.

For example let's say I have a custom form class that needs my custom javascript and/or css files.

class MyForm extends FormBase {
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['#attached']['library'][] = 'my_module/my_library'
    return $form;
  }
}


If you want to attach a library to an element you didn't initiate then you will need to use an alter hook for that specific element.
If you want to attach a library based on other conditions then you can use the hook_page_attachments(array &amp;$attachments) function