Mark Hood
11/20/2021, 10:19 PMGreg Brimble | Cloudflare Pages
11/20/2021, 10:19 PM/weather
?wonkrattle
11/20/2021, 10:19 PMwonkrattle
11/20/2021, 10:20 PMGreg Brimble | Cloudflare Pages
11/20/2021, 10:20 PMfunctions/index.ts
or functions/index.js
file, and yeah, we can use HTMLRewriter for it.wonkrattle
11/20/2021, 10:21 PMGreg Brimble | Cloudflare Pages
11/20/2021, 10:21 PMhtml
<p>
I also enjoy constructing
<a href="/crosswords">crossword puzzles</a>
.
</p>
<p>
I use
<a href="https://www.mynetdiary.com">MyNetDiary</a>
to track
<a href="/diet.html" style="color:#49D6EA !important;">what I eat</a>
.
</p>
<p id="weather">Could not load the weather</p>
</article>
Greg Brimble | Cloudflare Pages
11/20/2021, 10:21 PMGreg Brimble | Cloudflare Pages
11/20/2021, 10:26 PMjs
// ./functions/index.js
export const onRequestGet = ({ request, next }) => {
// Get the static asset response
const response = await next()
const { latitude, longitude } = request.cf
// Get weather
const weatherResponse = await fetch(`https://myweather.service/${latitude},${longitude}`)
const weatherData = await weatherResponse.json()
const { isRaining } = weatherData
// Find the placeholder in our static asset
return new HTMLRewriter().on('#weather', {
// And act on the element
element(element) {
// https://developers.cloudflare.com/workers/runtime-apis/html-rewriter#methods
element.setInnerContent(isRaining ? `It is raining 🌧` : 'It is not raining ☀️')
}
}).transform(response)
}
Greg Brimble | Cloudflare Pages
11/20/2021, 10:27 PMGreg Brimble | Cloudflare Pages
11/20/2021, 10:27 PMGreg Brimble | Cloudflare Pages
11/20/2021, 10:28 PMwonkrattle
11/20/2021, 10:28 PMGreg Brimble | Cloudflare Pages
11/20/2021, 10:28 PMGreg Brimble | Cloudflare Pages
11/20/2021, 10:29 PMfunctions/[path].js
it would act on all URLs like this:
- /
- /thing
- /weather
If it was functions/[[path]].js
it would act on all URLs, including these:
- /
- /thing
- /todos/thingGreg Brimble | Cloudflare Pages
11/20/2021, 10:30 PMwonkrattle
11/20/2021, 10:30 PMwonkrattle
11/20/2021, 10:30 PMGreg Brimble | Cloudflare Pages
11/20/2021, 10:31 PMGreg Brimble | Cloudflare Pages
11/20/2021, 10:31 PMGreg Brimble | Cloudflare Pages
11/20/2021, 10:31 PM/:product/:id
sort of thingwonkrattle
11/20/2021, 10:32 PMGreg Brimble | Cloudflare Pages
11/20/2021, 10:32 PMindex.html = index
William | Chaos Management
11/20/2021, 10:32 PMwrangler pages dev
because I imported another file as an ES ModuleGreg Brimble | Cloudflare Pages
11/20/2021, 10:33 PMWilliam | Chaos Management
11/20/2021, 10:33 PMGreg Brimble | Cloudflare Pages
11/20/2021, 10:33 PMGreg Brimble | Cloudflare Pages
11/20/2021, 10:33 PMWilliam | Chaos Management
11/20/2021, 10:33 PMwonkrattle
11/20/2021, 10:33 PM