What is the best way to craft an if/else statement for a situation when a twig variable is undefined?

When utilizing twig to declare a variable called user:

<script type="text/javascript>
   {% if user is defined %}
   var user = {
    example: {{ userjson | raw }}
   };
   {% endif %}
 </script>

If a user is not logged in, an error message appears on the console:

Uncaught ReferenceError: user is not defined

I am looking for a way to show a message when the user is not defined. Currently, I have the following setup:

if(user){
    console.log('hello');
} else {
    console.log('undefined');
}

// This code checks the user information
var userId = user.example.id;

console.log(user.example.money);

Answer №1

After some tinkering, I finally cracked the code:

<script type="text/javascript>
   {% if user is defined %}
   var user = {
    example: {{ userjson | raw }}
   };
   {% else %}
   var user = false;
   {% endif %}
 </script>

Now all I need to do is check if the variable 'user' is false, and if it's not, then I proceed with another action.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I am looking to generate div elements using JavaScript to avoid the tedious task of individually creating numerous divs

Instead of manually typing out multiple div tags in the HTML, I would like to dynamically generate them using JavaScript and display them on the page. Below is an attempt at achieving this, but it appears to not be functioning correctly. var arr = {}; f ...

Unable to invoke the 'apply' method on an undefined object when configuring directions for the jQuery Google Maps plugin

I've gone through the steps in a tutorial to create a jquery mobile google map canvas here, and have attempted to set it up. However, I keep encountering this error in my JavaScript console: Uncaught TypeError: Cannot call method 'apply' ...

How to Create Smooth Transitions for Text Arrays using jQuery's Fade In and Fade Out Features

I need to loop through an array of text and apply jQuery's fadeIn and fadeOut functions to each element. var greetings = ["hi, I'm", "bonjour, je m'appelle", "hallo, ich heiße"] The HTML structure I want is as follows: <h2><span ...

How can I showcase images stored in an array using JavaScript?

I am currently developing a role-playing game (RPG). In order to enhance the gameplay experience, I am trying to implement a for loop that will dynamically generate buttons on the screen. Here is the code snippet I have created so far: $(document).ready(f ...

Utilize the client-side JavaScript file with ejs framework

Recently, I have been working on creating a website using Express and EJS. I discovered that using just one JavaScript file for all my EJS (view) files was causing issues. If I target a DOM element in one view page and it doesn't exist in another, I w ...

What is the reason behind being able to assign unidentified properties to a literal object in TypeScript?

type ExpectedType = Array<{ name: number, gender?: string }> function go1(p: ExpectedType) { } function f() { const a = [{name: 1, age: 2}] go1(a) // no error shown go1([{name: 1, age: 2}]) // error displayed ...

Transitioning one element's opacity to zero while concurrently increasing another element's opacity to replace it

There are a total of 3 div elements and 3 links included in this setup. The goal is to only display one div at any given time. Upon clicking on a link corresponding to a different div, the current one should fade out while the selected one fades in seamle ...

Error occurred while attempting to parse JSON on comment system

I've run into some issues with my comments system. Everything was working perfectly yesterday, but today I started getting errors. I'm using json to post comments without reloading the page, but now I'm encountering a "SyntaxError: JSON.pars ...

The output type of a function given an input

Essentially, I have successfully rendered a return type for my combined reducers using the following code: const rootReducer = combineReducers({ notes: notesReducer, categories: categoriesReducer, flyout: flyoutReducer // more reducers }); export ...

Adding div elements using checkbox switch

In this code snippet, my aim is to display costs based on checkbox selection and generate corresponding totals in the bottom row when the checkboxes are toggled. The goal is to allow users to choose relevant items and have the total cost calculated accordi ...

Accessing Key / Value pairs of a JSON object using Newtonsoft Library

I've come across several questions and answers related to my current task, but despite reading through the responses, I'm still struggling to extract the key and value from this JSON. Here's the JSON data that is being returned: { "@odata. ...

A JavaScript object featuring a predefined value

I have a simple goal that I'm unsure about achieving. My objective is to create an object that will return a specific value if no property is specified. For example: console.log(obj) // Should output "123" console.log(obj.x) // Should output "ABC" ...

Is there a way to replicate table cells in the style of Excel using jQuery?

Excel has a convenient feature that allows cells to be copied by dragging and dropping with the mouse. This same functionality is also available in Google Spreadsheets. I am trying to understand how Google has implemented this feature using JavaScript cod ...

The specified project directory was not detected. Please restart Next.js in your updated directory

I am facing a challenge with running my NextJS web app on a VPS server with PM2 as the Process Management tool. Despite trying different approaches, I am unable to get it to run properly. I have a deploy.js file that successfully deploys my other NextJS an ...

Ionic 3 Storage Timing Explained

I have a scenario where I am trying to load JSON data from storage and display it on the HTML template of my page. However, when I try to do this, I encounter errors suggesting that the information is not yet available upon entering the page. I'm sta ...

What is the best way to keep track of a checkbox's value after unchecking it and then returning to the same slide?

Issue: By default, the checkbox is always set to true in the backend code. Even if I uncheck it using JavaScript, the value remains as true when switching between slides. Desired Outcome: If I uncheck the checkbox, the updated value should be saved so tha ...

error in jquery when splitting

I encountered an issue while trying to split data for checkboxes. var ukuran = data['model'].ukuran_model; var cek = ukuran.split(",").join('], [value='), $inputs = $('input[name^=ukuran]'); $inputs.filter('[value=&a ...

Using the v-for directive in Vue.js to loop through an array and display

Looking at the image provided, I am trying to access the content. I attempted to do so using element.comments.content, but it did not seem to work as expected. Here is the snippet of code: <div class="fil-actualites-container"> <div cl ...

Encountering ENOENT error when accessing view file in NodeJS and Express

I've encountered a strange issue with my nodeJS application after refactoring it. The app launches without any problems, the API responds correctly. However, when I attempt to access "/", I receive the following error: Error: ENOENT, stat '/view ...

The loading animation does not appear in the NextJS 14 - loading.tsx component while a GET request is being processed

Component with 500 photos displayed on my page: 'use client'; import { useEffect, useState } from 'react'; import { wait } from '@/components/loaders/skeletons'; export default function Postings() { const [photos, setPhotos ...