Hi,
In a LiveView app, I want to setup different meta tags for some pages. For example, on a user profile page, I want to add user specific meta title and description.
In mount function, I set :profile_meta
to true
def mount(_params, %{"user_token" => user_token} = _session, socket) do
current_user = Accounts.get_user_by_session_token(user_token)
{:ok,
socket
|> assign(:current_user, current_user)
|> assign(:profile_meta, true)}
end
In the head section I have the following:
<%= if @profile_meta do %>
<meta property="og:title" content={"#{@profile.name}"} />
<meta property="og:description" content={"#{@profile.about} "} />
<% else %>
...
When the profile page is opened in the browser, meta tags are loaded properly in the head tag as they should be.
The problem is that when sharing those page on social media, the data is not loaded because those websites don’t use javascript when scraping meta tags so mount function doesn’t happen and profile_meta: true
is never assigned.
What would be the best way to handle this?
There are two stages to LiveView mounting, dead render for standard http and live render for websocket connection. mount
is called each time and there’s no JS at play on the dead render, so you should be good.
1 Like
I thought so too, but it doesn’t work for some reason, just the default values are loaded (inside the else clause). And as I said, in the head tag when loading with browser, everything is loaded as it should.
Does it render if you liveSocket.disconnect()
on the JS console then view source? And is this in the root template? In a quick test I did it worked. Are you setting it anywhere like in a plug to deal that initializes it and maybe re-nilifying it? Is it in a layout that is only rendered by LiveView and not dead views? If it is in the root template then you should just write it as assigns[:profile_meta]
then you don’t have to worry about it being set. It’s ok to do this since LiveView doesn’t manage root (after the initial render).
I would also recommend the use of some site like https://www.opengraph.xyz/ to test if it isn’t a cache issue on the side of the social network.
1 Like