2

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->entityTypeManager->getViewBuilder('node');
$build       = $viewBuilder->view($node, 'full', $langcode);
$html        = $this->renderer->renderPlain($build);

Then I tried setConfigOverrideLanguage():

$this->languageManager->setConfigOverrideLanguage($language);

// … render the view here …

$this->languageManager->setConfigOverrideLanguage($originalLanguage);

But this did not work either. So it tried:

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

// … render the view here …

$this->configFactory->getEditable('system.site')->set('langcode', $originalLangcode)->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.

Your Answer

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

Browse other questions tagged or ask your own question.