Render a view in a given language in a custom command I have written a Drupal Console command that creates a huge batch of HTML snippets. This is done by rendering a view programmatically (as in this StackExchange answer)

The task

Now I have to create these snippets in several languages.

This works

If I call the view in my browser I can easily chose the language with the respective path prefix:

http://www.example.com/de/path/to/the/view (german version) 

http://www.example.com/en/path/to/the/view (english version)

This does not work

If I try to render the very same view from a Drupal Console command I am not able to set the target language. The rendered HTML is always in the default language.

At first I thought passing the langcode in the view() method should suffice:

// Now render the node as HTML
$viewBuilder = $this-&gt;entityTypeManager-&gt;getViewBuilder('node');
$build       = $viewBuilder-&gt;view($node, 'full', $langcode);
$html        = $this-&gt;renderer-&gt;renderPlain($build);


Then I tried setConfigOverrideLanguage():

$this-&gt;languageManager-&gt;setConfigOverrideLanguage($language);

// … render the view here …

$this-&gt;languageManager-&gt;setConfigOverrideLanguage($originalLanguage);


But this did not work either. So it tried:

$this-&gt;configFactory-&gt;getEditable('system.site')-&gt;set('langcode', $langcode)-&gt;save();

// … render the view here …

$this-&gt;configFactory-&gt;getEditable('system.site')-&gt;set('langcode', $originalLangcode)-&gt;save();


But I did not succeed. I even tried using a custom LanguageNegotiator, but I ran into a fatal error due to the fact that the service 'language_manager' does not implement the ConfigurableLanguageManagerInterface, so it is missing the setNegotiator() and getNegotiator() methods.

Once again I am totally stuck and I don't know what I am missing (most likely just a tiny bit). How in the world is it possible to change the language of my rendered HTML???

Edit 2017-01-05:

I have to admit I am quite desperate atm. I even tried everything I ruled out above again. Guess what, it still does not work. Any ideas? I am so shure that I am missing only a tiny piece. But I don't have any idea where to search for :(

Edit 2017-01-17:

Obviously the console command is not aware of (parts of) the context, even if I set the language. Just to get it done I am considering putting together a request object which I would then have been handled by the kernel. If this should turn out to be too complicated I could still curl the respective pages, but I have a feeling that there should be another way of doing this.

Edit 2017-03-14:

First of all there there has to be a translation (even if the node data is in no way language specific). If you want the complete context you have to use the Kernel's handle method with a sub request.
You should call:

Drupal::service("entity_field.manager")-&gt;clearCachedFieldDefinitions();


after language changes.