matestack / matestack-ui-core

Component based web UIs in pure Ruby for Rails. Boost your productivity & easily create component based web UIs in pure Ruby.
https://www.matestack.io
MIT License
545 stars 47 forks source link

Change page title #570

Closed sebyx07 closed 2 years ago

sebyx07 commented 2 years ago

Hey, how is it possible to change the page title while transitioning from a page to another? I want to assign the page title into a instance variable @title in the controller action

def index
  @title = "My Page"
end
jonasjabari commented 2 years ago

Hey @sebyx07!

We actually never had this requirement. But I totally understand the need to do so in some cases.

Which version of matestack-ui-core you're using? Teaser: You have to add a few lines of JavaScript within the callback of the page_loaded event for that ;)

sebyx07 commented 2 years ago

2.1.1 Sure no problem

jonasjabari commented 2 years ago

In you application.js add something like:

MatestackUiCore.eventHub.$on("page_loaded", function(){
  document.title = "Foo" // switch on location or query for a value within a page specific hidden element 
})

Does that help?

sebyx07 commented 2 years ago

Thanks for the inspiration. Here is what I came with:

in a concern.rb


included do
  after_action :__set_title_in_header
end

def title
  'New Title'
end

private

  def __set_title_in_header
    return unless request.format.symbol == :html
    response.set_header('Matestack-Title', title)
  end

in application.js

(function (){
  const defaultSend = XMLHttpRequest.prototype.send;
  XMLHttpRequest.prototype.send = function(...args) {
    const defaultLoad = this.onload;
    this.onload = (e) =>{
      if(defaultLoad) defaultSend(e);
      const title = e.target.getResponseHeader('Matestack-Title');
      if(title) document.title = title;
    }
    defaultSend.call(this, ...args);
  }
})();
jonasjabari commented 2 years ago

Looking interesting as well. Happy that you found a way to solve your issue. Closing this now :)