11ty / eleventy

A simpler site generator. Transforms a directory of templates (of varying types) into HTML.
https://www.11ty.dev/
MIT License
17.3k stars 496 forks source link

Conditionally render templates from Javascript #1008

Closed distich closed 1 year ago

distich commented 4 years ago

Hello folks!

Started using 11ty last week for a new project last week and I'm loving it so far!

Hit a snag though. Basically what I'm looking to do is use Firebase to confirm whether a user is logged in or not. From that confirmation I would like to conditionally display a specific template based on their logged in status.

I'm imagining that the final code would look something like:

{% if userLoggedIn %}
     {% include "partials/components/welcome.njk" %}
{% else %}
     {% include "partials/components/notloggedin.njk" %}
{% endif %}

Is this possible? I've gone at it a few different ways, read the docs and searched the issues. I'm sure it's right in front of my face but so far but nothing has worked for me. Any thoughts or nudges in a direction would be appreciated!

ghost commented 4 years ago

Hi, so Eleventy is a static site generator, meaning that at the time the HTML is generated it doesn't have the info on if a specific user is logged in or not.

What you could do is generate the HTML as if the user was logged out, and in JavaScript detect if the user is logged in or not. If the user is logged in then asynchronously load in the parts of the document that need to change. Since you are using Firebase these snippets could live there, or live as template tags in your original page.

Hope this helps.

distich commented 4 years ago

Hey Brent,

Thanks for the ideas! I had a similar thought and I've been trying to figure out something like what you're describing. However, I think where I always get caught up is how to handle the asynchronous loading you mentioned with template tags. I've tried a few different ways but I can't seem to get it.

Would you happen to have an example of how to handle that?

Thanks for your help!

ghost commented 4 years ago

Hi distich, I'm not near a computer right now but I will try to send an example tomorrow. When I have more than just my phone.

zachleat commented 1 year ago

The Serverless and Edge plugins should both be able to conditionally render things based on application state!

https://www.11ty.dev/docs/plugins/serverless/ https://www.11ty.dev/docs/plugins/edge/

I’d recommend the Edge one for this use case!