0

I am trying to parse variables using glue package in R. But looks like some issue. Can anyone please help

Since my variables here will be reactive in future , I am trying to parse it using glue...............................................

library(glue)
asd <- "XYZ"


HTML(glue('<html>
<head>
<style>
.dropdown {
  position: relative;
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f9f9f9;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
  padding: 12px 16px;
  z-index: 1;
}

.dropdown:hover .dropdown-content {
  display: block;
}
</style>
</head>
<body>



<div class="dropdown">
  <span>{asd}</span>
  <div class="dropdown-content">
  <p>Hello World!</p>
  </div>
</div>

</body>
</html>
'))
Error in eval(parse(text = text, keep.source = FALSE), envir) : 
  object 'position' not found

expected output

<html>
<head>
<style>
.dropdown {
  position: relative;
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f9f9f9;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
  padding: 12px 16px;
  z-index: 1;
}

.dropdown:hover .dropdown-content {
  display: block;
}
</style>
</head>
<body>



<div class="dropdown">
  <span>XYZ</span>
  <div class="dropdown-content">
  <p>Hello World!</p>
  </div>
</div>

</body>
</html>

I am trying to parse variables using glue package in R. But looks like some issue. Can anyone please help

Since my variables here will be reactive in future , I am trying to parse it using glue...............................................

manu p
  • 952
  • 4
  • 10

1 Answers1

2

sprintf should work here

str1 <- sprintf('<html>
<head>
<style>
.dropdown {
  position: relative;
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f9f9f9;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
  padding: 12px 16px;
  z-index: 1;
}

.dropdown:hover .dropdown-content {
  display: block;
}
</style>
</head>
<body>



<div class="dropdown">
  <span>%s</span>
  <div class="dropdown-content">
  <p>Hello World!</p>
  </div>
</div>

</body>
</html>
', asd)

The error in the OP's code is from the eval(parse which it uses in .transformer argument. By default it goes into identity_transformer and this eval/parsing of the whole string thus creates an issue. It may be better to use sprintf or create a custom .transformer function

akrun
  • 874,273
  • 37
  • 540
  • 662
  • Thanks... But not sure what is wrong in my code if I use glue. Can you try? Or else can anyone who knows glue help me – manu p Oct 19 '21 at 07:12
  • @manup you may use a raw string `r` – akrun Oct 19 '21 at 07:12
  • @manup it is related to `.transformer` which does evaluate to an [identity_transformer](https://github.com/tidyverse/glue/blob/master/R/transformer.R) – akrun Oct 19 '21 at 07:20