[FastAPI] Using JS to provide onclick event within inside a Jinja2 loop

THOVY·2023년 3월 4일
0

TROUBLESHOOTING

목록 보기
35/41
post-thumbnail

Using Python(FastAPI) / Jinja2

<!-- index.html -->

<body>
  <div>
    {% for chat in chats %}
      	<div>{{ chat.contents }}</div>
    	<button
        	onClick=getId(chat.id) 
        >
          	print this chat_id out
    	</button>
    {% endfor %}
  </div>
  
  ...
  
  <script>
    function getId(id){
      console.log(id)
    }
  </script>
</body>

How Can I get the ChatId

  1. Let's create a button
    make the button to print the chatId on the console when click event occurs
  1. but just putting chat.id in the event properties does not work.
  1. So we have to put the chat.id in HTMLButtonElement as the Error says.
<!-- index.html -->

<body>
  <div>
    {% for chat in chats %}
      	<div>{{ chat.contents }}</div>
    	<button
            id={{chat.id}}		
            onClick=getId(id)	
        >
          	print this chat_id out
    	</button>
    {% endfor %}
  </div>
  
  ...
  
  <script>
    function getId(id){
      console.log(id)
    }
  </script>
</body>
  1. As in the example, put {{chat.id}} obratined by Jinja Loop into id, you have to put id in the event property.
    But you can not write this,
	<button
        id=getChatIdBtn
		name={{chat.id}}	
		onClick=getId(name)	
	>

you can get nothing.

if you write on right element.

🙋‍♂️ 타란~

profile
BEAT A SHOTGUN

0개의 댓글