模具中访问请求的URL参数 [英] Access request's URL parameters in stencil
问题描述
我可以在模具中访问请求的查询参数吗?因此,如果您转到 http://example.com/?name=Bob 我可以渲染类似的东西吗?
Can I access the request’s query params in stencil? So if you go to http://example.com/?name=Bob Can I render something like:
Hello {{url.name}}!
它必须是服务器端呈现的,而不是浏览器JavaScript.
It has to be server-side rendered, not browser JavaScript.
为什么?好吧,我实际上想在Facebook上分享测验的结果,因此 og:image
标记需要指向分数图片.因此,我分享了一个链接,例如 http://example.com/quiz/?quizScore=encodedscoreresult,然后页面包含:
Why? Well, I actually want to share the results of a quiz on Facebook, so the og:image
tag needs to point at a picture of the score. So I share a link like http://example.com/quiz/?quizScore=encodedscoreresult and the page then contains:
<meta property="og:image"
content="https://myapi.example.com/quizresultsimage?quizScore=encodedscoreresult" />
推荐答案
不是完整的解决方案,因为您无法访问单个参数的值,但是...
Not a full solution, as you can't access an individual parameter's value, but...
settings.facebook_like_button.href
确实包含请求URL,URL编码为 https%3A%2F%2Fexample.com%2Fquiz%3FquizScore%3Dencodedscoreresult
The settings.facebook_like_button.href
does contain the request URL, URL encoded as https%3A%2F%2Fexample.com%2Fquiz%3FquizScore%3Dencodedscoreresult
您可以使用以下方法从URL中提取整个查询字符串:
You can extract the whole query string from the URL using:
<meta property="og:image"
content="https://myapi.example.com/quizresultsimage{{get "search" (getObject "search" (urlParse (decodeURI settings.facebook_like_button.href)))}}" />
但是,这将包括所有查询参数,因此可能会带来安全风险,即将不需要的额外参数从模板站点传递到api.
However, that will include all the query parameters, so that may be a security risk passing extra parameters from your stencil site to the api that aren't desired.
更简单(也许更安全),您可以将整个URL作为参数传递给meta标记,然后API必须对其进行解码:
Simpler (and perhaps safer), you can pass the whole URL as a parameter in the meta tag, and then the API will have to decode it:
<meta property="og:image"
content="https://myapi.example.com/quizresultsimage?url={{settings.facebook_like_button.href}}" />
结果为:
<meta property="og:image"
content="https://myapi.example.com/quizresultsimage?url=https%3A%2F%2Fexample.com%2Fquiz%3FquizScore%3Dencodedscoreresult" />
由于查询字符串中只有一个参数,因此可以确保没有向目标URL传递不需要的任何内容.
Because there is only one parameter in the query string, you can be sure you're not passing anything undesired to the target URL.
如果您只需要解码的URL,则可以使用:
If you just need the decoded URL you can use:
{{assignVar "requestUrl" (decodeURI settings.facebook_like_button.href) }}
{{getVar "requestUrl"}}
这篇关于模具中访问请求的URL参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!