nuxt-modules / og-image

Generate OG Images with Vue templates in Nuxt.
https://nuxtseo.com/og-image
417 stars 28 forks source link

help: Get access to generated OgImage path #264

Open julbd opened 1 month ago

julbd commented 1 month ago

📚 What are you trying to do?

Hello,

I'm looking for a way to get the path to an ogImage without actually defining it as the ogImage of the current page. The objective is to provide the user a "screenshot" of a component in full static.

Something like (pseudo-code) :

<template>
    <img src="{{ogImagePath}}" />
</template>

<script setup>
    const ogImagePath = useOgImageComponent('NuxtSeo');
</script>

Thanks. 🤗

🔍 What have you tried?

No response

ℹī¸ Additional context

No response

harlan-zw commented 1 month ago

Hi, thanks for the issue.

I may look to add a composable as you've described or alternatively just return the meta data from the defineOgImage composable if more people need it.

For the time being you can use this code.

export function getOgImagePath(pagePath?: string, _options?: Partial<Pick<OgImageOptions, 'extension'>>) {
  const runtimeConfig = useRuntimeConfig()
  const { baseURL } = runtimeConfig.app
  const route = useRoute()
  const options = defu(_options, runtimeConfig['nuxt-og-image'].defaults)
  return joinURL('/', baseURL, `__og-image__/${import.meta.prerender ? 'static' : 'image'}`, pagePath || route.path, `og.${options.extension}`)
}
<template>
    <img src="{{ogImagePath}}" />
</template>

<script setup>
    defineOgImageComponent('NuxtSeo', { /* ... */ })
    const ogImagePath = getOgImagePath();
</script>
martinadamsdev commented 1 month ago
export function getOgImagePath(pagePath?: string, _options?: Partial<Pick<OgImageOptions, 'extension'>>) {
  const runtimeConfig = useRuntimeConfig()
  const { baseURL } = runtimeConfig.app
  const route = useRoute()
  const options = defu(_options, runtimeConfig['nuxt-og-image'].defaults)
  return joinURL('/', baseURL, `__og-image__/${import.meta.prerender ? 'static' : 'image'}`, pagePath || route.path, `og.${options.extension}`)
}

@harlan-zw

Your reply is very helpful to me. Thank you very much. I have a website that has many paths that need a unified style. How can I change the __og-image__ path? eg:

`/${import.meta.prerender ? 'static' : 'image'}`, pagePath || route.path, `og.${options.extension}`