Live Preview for Upcoming Entries I have an Events section on my site, and to display upcoming and passed events (entries with a status of pending or expired) I manually set the entry in the template:

Where the URL is /events/my-event-title

{% set entry = craft.entries({
    section: 'Events',
    slug: craft.app.request.segment(2),
    status: ['live','pending','expired']
}).one %}

&lt;h1&gt;{{ entry.title }}&lt;/h1&gt;

{{ entry.body }}


This works great except when I go to publish a new Event and use the Live Preview. Since the new entry doesn't have a slug yet, the craft.app.request.segment(2) variable returns null, and so entry returns the last-published Event entry instead. So all of my template variables are pre-populated with a different entry's content.

How do I set this up so my Live Preview displays blank until I enter content?
If your “event” Entry's Section settings define a URI and a template path, Craft will take care of defining entry in the template. No need to look it up by segment!

Generally speaking, this will “just work” for Live Preview, as well.

 I'd recommend setting the Event Section's Template to _events/event, and creating templates/_events/event.twig in your project folder. Then, entry will be automatically available when the template is rendered, either from a front-end request, or via Live Preview.

I can't speak exactly to the internals of Live Preview—but I can say that it side-steps the normal routing by laterally POSTing the updated content to a Craft Controller that independently resolves and renders the template. That said, once it starts rendering the template, it's almost exactly the same context you'll get when the Entry is live, and requested via its normal URL.


   Using an underscore in the template's path will make sure the template is not directly accessible, and is only rendered during a request that Craft has determined matches an Element (in your case, the event Entry), or via the Live Preview controller. Read more about how Craft routes requests, here.