0

I'm trying to output a JS based frontend app through one controller action.

To achieve this I need this action to output a very specific html layout, inlcuding some js files.

As far as i know I can return a symfony response object to bypass drupals render stack, inlcuding themeing mechanism. But how to deal with the js files that should be included? Right now they are located inside my module folder, and I definitly don't want to link to this location inside my custom html output.

1
  • 1
    You need to create a library (mymodule.libraries.yml) and then attach it. See Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 module. PS: yml files are picky about spaces, so make sure you get those right and do not use the tab key, use the space bar key instead. Probably better off copy and pasting the example and just modify.
    – No Sssweat
    May 19 '17 at 11:38
0

If i understand u want to output custom HTML for module, for smoething like this best practice is to preprocess output with twig template, in twig u can generate custom HTML for your needs and of course attach js and css with libraries. See: Theme system overview.

2
  • I'm aware of the theme system but i thought it would be easier and more efficient if my static html isn't processed by drupal since there is no need for it to do so... May 19 '17 at 11:56
  • If you don't want Drupal to process your pages, what's the question @LeonhardBrunner? Is it simply "where do I put JS files I don't want to serve from a module folder?"?
    – Clive
    May 19 '17 at 11:57
0

Like mentioned in a comment above, you need a my_module.libraries.yml in your module. As an example: Your js files are situated in the folder ./modules/my_module/app. Then your YAML should looks so:

my_custom_library:
  js:
    app/main.js: {}
    app/router.js: {}

And in your module you can attach the file when it is needed. For instance in a preprocess hook:

my_module_preprocess_node(&$variables) {
  $variables['#attached']['library'][] = 'my_module/my_custom_library';
}

Clear cache and your library will be loaded when nodes are on the page.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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