Page 2 of 21

Rust Primitive Data types

Rust variables are immutable by default.

Variables must be explicitly declared as mutable using mut keyword

Rust is a statically typed language – all variable data types must be know at compile time.

Example-

//default immutable. value cannot be changed after declaration
let x = 10; 

// marked as mutable. i.e value can be changed after declaration
let mut y = 20; 

Compiler Errors-

let x = 10;
println!("x is {}", x);
x=20; // Error. Cannot be assigned twice. consider making this muttable
println!("x is {}", x);

Solution-

let mut x = 10; // make this mutable
println!("x is {}", x);
x=20; // compiles successfully
println!("x is {}", x);

Reference

https://doc.rust-lang.org/1.0.0/style/style/naming/README.html

https://rust-lang.github.io/api-guidelines/naming.html

Integer Data Types

Reference https://doc.rust-lang.org/reference/types/numeric.html

  • Unsigned – only represent positive values
  • Signed – represent positive and negative values
  • Characterized by number of bits
LengthSignedUnsigned
8-biti8 ( -(27) to 27-1)u8 ( 0 to 28-1)
16-biti16 ( -(215) to 215-1)u16 ( 0 to 216-1)
32-biti32 ( -(231) to 231-1) defaultu32 ( 0 to 232-1)
64-biti64 ( -(263) to 263-1)u64 ( 0 to 264-1)
128-biti128 ( -(2127) to 2127-1)u128 ( 0 to 2128-1)

Type of the varaible is declared after the : (colon)

Example:-

// signed 8-bit integer. max value can hold is 255
let x: i8 = 255;
let y: i8 = -10;

// unsigned 8-bit integer.
let z: u8 = 255;

Compiler Errors-

// unsigned 8-bit integer. max value 255
let z: u8 = 256;

Solution-

// unsigned 8-bit integer. max value 255
let z: u8 = 255; // compiles successfully

Runtime Errors-

// unsigned 8-bit integer. max value 255
let mut z: u8 = 255;
z = z + 1; // Error: panicked - attempt to add with overflow
println!("z is {}", z);

Solution-

// unsigned 8-bit integer. max value 255
let mut z: u8 = 254;
z = z + 1; // compiles and runs successfully
println!("z is {}", z);

Output- z is 255

Floating-Point Data Types

  • Represent numbers with decimal points
  • f32 and f64 are two floating-point types
  • Value stored as fractional and exponential components

f32- represents value from 6 to 9 decimal digits of precision.

f64- represents value from 15 to 17 decimal digits of precision.

Example-

let x= 10.00; // default is f64
println!("x is {} deafult type is f64", x);

let y: f32= 10.1234567890132456798; // default is f64
println!("y is {} with f32 floating-point type", y);

let z: f64= 10.1234567890132456798; // default is f64
println!("z is {} with f64 floating-point type", z);

Output-

x is 10 deafult type is f64
y is 10.123457 with f32 floating-point type
z is 10.123456789013245 with f64 floating-point type

Guidelines for Numeric data types

Values with fractional component or decimal places use floating-point data type.

Use f64 or been dfault gived most precision range. With modern computers it is as good as using f32. So perrfomance should not be an issue.

Use f32 with embedded systems where memory is a limitation.

Default 32 signed integer (i32) provides a genrous range – between amd aroung plus or minus 2 billion

For memory concerns use smaller size integers to conserve and use less memory

Arithmetic Operations

Rust uses arithmetic operations with the operators +, -, *, / and %

Artihmentic operation results depend on the type of variables. example, if both operators are integer then will get result in integer

let x= 10; // default is i32
let y=3; // default is i32
let z= x / y;
println!("z is {}", z) // so z will be i32

Output- Here the value of z is 3 since both the variables are defaulted to signed integer i.e. i32

z is 3

Now if we add decimals to x and y the output is floating-point-

let x= 10.00; // default is f64
let y=3.00;
let z= x / y;
println!("z is {}", z)

Output- Here the default is f64.

z is 3.3333333333333335

Compiler Errors-

If one of the variables data type is different from other, then will receive error-

let x= 10; // default is i32
let y=3.00; // default is f64s
let z= x / y;
println!("z is {}", z)   

Here the default integer is i32 and floating-point is f64. Dividing different data types will result in error. This is applicable for all artihmetice operations.

Solution-

For the above error cast the variable.

 let x= 10; // default is i32
 let y=3.00; // default is f64s
 let z= x as f64 + y;
 println!("z is {}", z)  

Output-

z is 3.3333333333333335

Formatting print statements

Reference- https://doc.rust-lang.org/std/fmt/

To format the data use Module fmt. This uses the formatting extensions.

Use {} as argument to print the values

Examples-

 println!("Hello {}!", "world"); // prints-  Hello world!
 //named parameters
 println!("{value}", value=10); // prints- 10

 // named paarameters using variable
 let name = "Sandeep Pote";
 println!("Name: {name}");

 // Decimal point upto 3
 let z= 3.33333335;
 println!("z is {:.3}", z);  // prints - 3.333

 // Upto 3 decimal places with lenth of 8 and preceding 0's
 println!("z is {:08.3}", z);  // prints- 0003.333

Output-

Hello world!
10
Name: Sandeep Pote
z is 3.333
z is 0003.333

Positional Parameters

Here the first_name and last_name are named parameters, but the position of printing the parameters are set in different order

println!("{last_name} {first_name}", first_name="Sandeep", last_name="Pote"); //Prints- Pote Sandeep

Binary

Binary trait formats the output as a number in binary

Example-

let value= 0b11110101u8;
println!("value is {}", value)// Prints the number
println!("value is {:b}", value) // prints the binary
println!("value is {:010b}", value) // prints the binary upto 10 digits and preceding 0.

Output-

value is 245
value is 11110101
value is 0011110101

Here the binary is converted to number. The prefix 0b mentions the value is binary and suffix u8 converts the binary to unsigned integer.

Bitwise operations-

Logical operations on patterns using NOT, AND, OR, XOR and SHIFT.

Taking the above example, Bitwise NOT-

let mut value= 0b11110101u8;
value=!value;
println!("value is {:08b}", value); // prints the negated binary

Output-

value is 00001010

Bitwise AND- change the value of a specific Bit-

Use the & with the anotehr binary to change the value.

Example- to change the value of the highlighted 11110111 to 0, & this with 11110011. Ouput will be 11110011

Example-

let mut value= 0b11110111u8;
value=value & 0b11110011;
println!("value is {:08b}", value); 

Output-

value is 11110011

Likewise use | (pipe) for OR, ^ for XOR, << Left shift and >> Right Shift

Boolean data types and operations

Use the above operatos used in bitwise for boolean operations.

Example-

let a = true;
let b= false;
println!("a is {} and b is {}", a, b);
println!("NOT a is {} ", !a);
println!("a AND b is {} ", a & b);
println!("a OR b is {} ", a | b);
println!("a XOR b is {} ", a ^ b);

Output-

a is true and b is false
NOT a is false 
a AND b is false 
a OR b is true 
a XOR b is true 

Short-Circuiting Logical Operations

With this in OR operation if the left side is True then it won’t check the right side since the result for OR will be always true.

Similarly, for AND operation if the left side is False, it won’t check the value at the right side, since the result will be always False.

This can be done using && or ||. This improves the code effeciency.

Example-

let a = true;
let b= false;
let c= (a ^ b) || (a & b);
println!("c is {}", c);

Output-

c is true // (a ^ b) is true || (a & b) is false

Comparision Operations

Reference – https://doc.rust-lang.org/book/appendix-02-operators.html

Use compareision operators to compare values. Some of these are-

  • Equal ==
  • Not Equal !=
  • Greater Than >
  • Less Than <
  • Greater Than Equal >=
  • Less Than Equal <=

Example-

let a = 1;
let b= 2;
println!("a is {} and b is {}", a, b);
println!("a EQUAL TO b is {} ", a == b);
println!("a NOT EQUAL TO b is {} ", a != b);
println!("a GREATER THAN TO b is {} ", a > b);
println!("a LESS THAN TO b is {} ", a < b);
println!("a GREATER THAN EQUAL TO b is {} ", a >= b);
println!("a LESS THAN EQUAL TO b is {} ", a <= b);

Output-

a is 1 and b is 2
a EQUAL TO b is false 
a NOT EQUAL TO b is true 
a GREATER THAN TO b is false 
a LESS THAN TO b is true 
a GREATER THAN EQUAL TO b is false 
a LESS THAN EQUAL TO b is true 

The comparision can be used with the similar data types.

Char Data Type

  • Represents a single character
  • Stored using 4 bytes
  • Unicode scalar value

Char can be represented within a single quote e.g.- ‘a’

Unicode characters can be represented using “\u{hexa decimal value}”

Reference- https://home.unicode.org/

Example-

let letter = 'a';
let number = '1';
let unicode= '\u{0024}';
println!("Letter is {}", letter);
println!("Number is {}", number);
println!("Unicode is {}", unicode);

Output-

Letter is a
Number is 1
Unicode is $

Loading

Sitecore Headless SXA – Create, apply and restrict a custom style to renderings

In this blog post I will show how to apply a custom style to a rendering.

Requirement-

I have a requirement to add extra spacing between the components.

There is already a indent-top style which provides this space (20px) but neesd 100px space.

And the same can see in Experience Editor-

Same can also see in css file in sxastarter project-

Create a custom style (indent-large-top)

Create custom style in Sitecore-

Create a new style (Indent Large Top) in Sitecore under Presentations => Styles ==> Spacing

/sitecore/content/scxmcloud/sxastarter/Presentation/Styles/Spacing

Provide the value of the Style-

Create a style in FE project with the same value-

There are various ways you should be able to do this. I am adding 5 times more space to the existing indent-top style.

_indent.scss

// $middle-margin is defined in _margins.scss
.indent-large-top {
  margin-top: calc($middle-margin * 5);
}

Apply a custom style to rendering

Select the component or container you want to apply style and choose option “Indent Large Top” in Spacing section

Now the space between the 2 component is increased and is 100px as per the requirement.

New style applied to container-

Apply style to specific renderings

As above when the style was created it was applied to all renderings.

If you want to restrict the style to be applied to only certain renderings you can do so by setting Allowed renderings field in new created Style item.

For “Indent Large Top” only SectionContainer will be able to see the new Spacing Style.

In Experience Editor you wont see the “Indent Large Top” for other renderings e.g.- for container rendering-

While for Section Container rendering the new style is available-

References-

https://doc.sitecore.com/xp/en/developers/sxa/103/sitecore-experience-accelerator/add-a-style-for-a-rendering.html

Loading

Guide to avoid scam with crypto

Keep self-custody of your crypto asset

For Noncustodial wallets keep your recovery code safe

Don’t fall in trap if wallet application asks for recovery code for no reasonRecovery code is asked while creating a wallet i.e. initial setup or if you have lost your wallet i.e. recovery – other than that ensure that you are been not phished

Don’t keep all you crypto assets in a single address

Don’t share the same address to multiple person – Private keys are used to generate the Bitcoin Address. For each transaction create a new address. This way you avoid anybody to know how much bitcoin has been sent to that address in total. Generating new address everytime also protects your privacy.

Block explorer privacy – Block explorer is a web appplication that operates as a Bitcoin search engine. You can search by Bitcoin addresse, transaction hash, block number and block hash. Using these applications and searching a transaction allows them to associate the IP address, previous earches and browser details through which can identify and learn your activities. Searching somebody else transaction should not be a problem but if you search your own transactions these operators might be able to analyse the Bitcoin your have received and spent or currently own. So as mentioned earleir each transaction should be on different address to make the operators difficult to identify you.

Ways to acquire a Bitcoin as a new user

Bitcoin transactions are irreversible. So be careful when doing transaction either send or receive. Since the transactions are done on address and there is not identity attached, there is no verification process to check if the address is your’s before doing a transaction. This way acquring, holding and spending bitcoin does not expose your personal identity. Although everybody in the network can see the how much bitcoin is in a address but that address doesn’t disclose your identity. As a new user follow this guidelines-

  • First do a self study how the crypto transaction works. With most of the mobile apps its as as easy as transfering the fiat currency. But if you have a self custodial assets its very important to understand the process. Understand the current Price of bitcoin from the currency exchange, transaction fees, location from where you will be doing transactions. It is good to understand the rules and regulations of the country where you reside.
  • Get introduction about bitcoin from a friend – Take help from you friend who already has Bitcoin and buy from your them directly with a small amount. This should give you a confidence when doing further transactions by yourself. Once you are familiarised and have confidently done transactions help new users and share your expereince.
  • Earn a bitcoin. Earn a bitcoin by providing service with which ever profession you are in. Example- if you are porgrammer you sell your skills for firat currency, instead sell your service for bitcoin. This requires to share your adddress along with the invoice to your client who should then send agreed bitcoin to your address. This way you learn how to generate address to receive bitcoin. Always remember to genereate new address for each invoice. See section “Don’t share the same address to multiple person“.
  • Use Bitcoin ATM – A Bitcoin ATM is a standalone device or kiosk that allows you to buy or sell bitcoin or other cryptocurrencies using a terminal. Bitcoin ATMs are connected to the Internet and often utilize QR codes to send and receive tokens to users’ digital wallets. Bitcoin ATM accepts cash and send bitcoins to your wallet. This way you get to familiarise with bitcoin transaction’s.
  • Use Bitcoin currency eschange – you can buy bitcoin from the digital curerncy exchange such as Coinbase which is linked to your back account. Although they will take the transaction fees but a safe way to buy or sell the bitcoins.

Generating Private Key

Do not write your own code to create a random number or use a simple random number generator offered by programming language. Use CSPRNG (crytpographically secure pseudorandom number generator) with a seed from a source of sufficient entropy. What is entropy – see here blog post of private key

Loading

How to set background image using Next js in Sitecore XM Cloud

This is a very common scenario where a background image needs to be set to certain components. Banner’s on any page on your website is a very common place to have a background image.

This blog assumes you have setup the Foundation Head setup or have your own Nextjs project setup implemented using the Sitecore NextJS SDK.

Note: This is not specific to XM Cloud but for any Headless implementation

Foundation Head already has an example on setting the background image using params. In this blog post will explore how this works and where in Sitecore the image can be applied. Will see how this can applied using using OOTB _Background Image item.

To apply image background using rendering parameters to the container see this blog here

Applying background image using rendering field to the components

Background image can be applied to components inheriting the existing __Background Image item to the custom component template.

Create a template for your component. Here I am creating a Banner component-

Inherit _Background Image from /sitecore/templates/Foundation/Experience Accelerator/Presentation/_Background Image

_Background Image has “Background Image” and “Stretch mode” field.

Note that there is a space between the field names, although not recommended but this comes OOTB.

Create a “Banner” JSON Rendering and provide the “Parameters Template”, “Datasource Location” and “Datasource Template” as per your requirement and add this rendering to the “Available Renderings”

Create a Nextjs component in sxastarter project

Note below how the “Background Image” field is set. This is due to the same in field name. Not recommended but this is OOTB.

View this gist on GitHub

Experience Editor-

Add a container component in Main placeholder-

Add a newly created component (Banner) in Container placeholder-

Create or select associated content

Once the component is added you should see the button to Add Background Image ( ths is added when the template inherits from _Background Image template.

Select the Background Image and Save-

You should now able to see the background image to component-

Rendering Host-

Reference-

https://doc.sitecore.com/xmc/en/users/xm-cloud/add-a-background-image.html

First Rust project using cargo package manager

If this is the first time you are using Rust you will have to install Rust on your Windows machine.

To install see this link – https://www.rust-lang.org/tools/install

To install Rust on Windows sybsystem for Linux, use this shell command-

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

Check the version of Rust-

rustup --version

Check the version of Rust compiler

rustc --version

To update the Rust, use following command-

rustup update

Create a main.rs file and add code to print a string

fun main(){
    println!("Hello World!")
}

Compile using rust compiler

rustc main.rs

This should create a pdb and exe file

Execute the main.exe file and this should print the string

Create a Rust project using Cargo

Cargo is a build and package manager.

  • Helps to manage dependecies for repetable builds
  • Downloads and builds external libraries
  • calls rustc with correct parameters
  • Included with standard rustup installation

For creating a new Rust project using Cargo package manager-

cargo new first_rust_prj

Tip – The name of the project should be snake case. Example this will give a warning. Atlhough this will create a project.

cargo new FirstRustPrj //Warning
 
Creating binary (application) `FirstRustPrj` package
warning: the name `FirstRustPrj` is not snake_case or kebab-case which is recommended for package names, consider `firstrustprj`

This should create following folder structure with main.rs and Cargo.toml (configuration) file.

TOML – Tom’s Obvoius Minimal Language.

Alternatively, you can create a project without using Cargo. Create a src directory and create appropriate Cargo.toml namually. To create toml file use init command

cargo init

Building and Running Cargo project

Build the Cargo project using following command-

cargo build

To compile and run directly from the project folder, use following command-

cargo run

Error compiling the project-

error: linker link.exe not found

So the pre-requisite for windows machine is to have MS C++ build tools. Install the smae from here. It should be around 5 GB.

https://visualstudio.microsoft.com/visual-cpp-build-tools

Now this should run the project –

To check the code without producing an executable use follwoing command-

cargo check

Building for Release

Use following command when project is ready for release-

cargo build --release

IDE to develop rust-

Visual Studio Code

Install Visual Studio Code. Then install rust-analyzer for code auto completion, hints and code actions – Link

See here the IDE’s the rust analyser supports.

Rust Rover

IDE by Jet Brains – here. This is free for non-commercial users.

References-

https://doc.rust-lang.org/book/ch01-01-installation.html#installing-rustup-on-linux-or-macos

Loading

All about Rust Cargo commands

Cargo is Rust’s build system and package manager. Most developers use this tool to manage their Rust projects because Cargo handles a lot of tasks for you, such as building your code, downloading the libraries your code depends on, and building those libraries.

Cargo commands and its usage-

Check the cargo version

cargo --version

Create a new project

Create a new project using Cargo.

cargo new <<project_name>>

Build the Cargo project

Build command compiles the project and create’s an executable file in /debug/ folder. Running the cargo build command updated the Cargo.lock file which keeps the trakc of exact version of dependecies in the project.

cargo build

Running a Cargo project

Cargo run compiles the project and runs the resultant executable all in one command. So instead of remembering the cargo build and path to execute the excutable, Cargo run does both for you which is more conveninent

cargo run

Check your code

If you want to quickly check if the code to make sure it complies susccesfully without using build or run command, you can use check command. This nmusch faster than build because it skips the step to create an executable.

cargo check

Update the project dependencies

Update the dependeincies of you project using update command. This ignores the Cargo.lock file which has all the dependencies. update command will look for one higher version than current version e..g: if the current version is 0.7.5 and the latest version is 0.8.0. But if there is next higher version i.e. 0.7.6, then update command will udpate the dependency to 0.7.6. Also after update the Cargo.lock file is udpated.

If you want to jump to a specific version, as per above case to 0.8.0. Update hte Cargo.toml file dependencies section.

cargo update

Reference – https://doc.rust-lang.org/cargo/

This is WIP, there is lot more to add here.

Loading

Bitcoin Notes

Bitcoin is a internet of money. Invented in 2008. Started in 2009

Bitcoin consists of –

  • Bitcoin Protocol – A denetralized peer-to-peer network
  • Blockchain – Public transaction ledger
  • Consensus rule – Set of rules for independent transaction validation and currency issuance
  • Proof-of-Work – Distributed computation system.

Mining– A decentralized mathematical and deterministic currency issuance. Competing to find solutions to a mathematical problem while processing bitcoin transactions (power to verify and record transactions) which is done every 10 minutes. Transactions become a part of blockchain and is included in a block by a miner, that process is called as mining

The mining process serves two purposes
in bitcoin:

  • Mining nodes validate all transactions by reference to bitcoin’s consensus rules.
    Therefore, mining provides security for bitcoin transactions by rejecting invalid
    or malformed transactions.
  • Mining creates new bitcoin in each block, almost like a central bank printing new
    money. The amount of bitcoin created per block is limited and diminishes with
    time, following a fixed issuance schedule

Mining uses electricity hsnece they has to be rewarded with a new bitcoin and any transaction fees. These provides security for Bitcoin without any central authority. Mining is a decentralized lottery system. Each miner create their own lottery ticket by creating a candidate block whihc includes new transactions which they want to mine. Do you know miner has to try 168 billion trillion candidate blocks before finding the winning combination.

Once the winning combination is found which takes a incredible work but other peers take trival amount of work to verify to prove the work was done, the winning block is the proof the work was done and is called as proof-of-work.

Transaction script – A decentralized transaction verification system.

Paper title – “Bitcoin: A Peer-to-Peer Electronic Cash System” written by Satoshi Nakamoto.

Fast, Secure and Borderless. Distributed, peer-to-peer system. No central server or point of control. Created through a process called as mining.

Bitcoin is completely decentralised by design and free of any central authority or point of control that can be attacked or corrupted.

Every 10 minutes or so, Mining computers compete against thousands of similar systems in a global race to find a solution to a block of transactions. Finding such a solution, the so called Proof-of-Work (PoW)

Fixed total 21 millions coins will be created by the year 2140.

Bitcoin is virtual. User of bitcoin own keys that allow then to prove ownership stored in digital wallet.

Block #0 is known as genesis block.

Application Specific Integrated Circuits (ASIC)

Unverified transactions when included in a new block it is called as candidate block.

Bitcoin Improvement Proposal

Important Notes-

  • Bitcoin currency will defalte in long term as the rate of issuance will reduce and ultimately diminish.
  • Bitcoin is not a physical or digital coins. The coins are implied in transactions that can be transfered from sender to receipient.
  • Bitcoin users can transfer funds using the keys that a re stored in digital wallet/ledger. They need to sign a tranasction to unlock the value and spend it by transfering the funds. key that can sign the transactions is the only pre-requisite to spend bitcoin.

Types of wallets-

  • Desktop Wallet
  • Mobile Wallet
  • Web Wallet
  • Hardware signing devices (Harware wallet – most secure)

Full node versus lightweight

  • Full node – offers complete autonomy to its users (self governance)
  • Lightweight client. simplified-payment-verification (SPV)
  • Third-party API client

Nodes

Peers in the Bitcoin peer-to-peer network are programs that have both software logic and necessary data that fully verify the correctness of new transactions. The connection between peers are visualized as edges(lines) in a graph with the peers themselves being the node (dots) Bitcoin peers are commonly called “full verification nodes” or full nodes for short.

What is gossiping

Any Bitcoin node that receives a valid transaction it has not seen before will forward it to all other nodes (peers) to which it is connected. This propagation technique is know as gossiping.

Abbrevations –

  • SPV – Simplified Payment Verification
  • NFC – Near field communication
  • POW – Proof of work
  • P2P – peer-to-peer network

Computing problems –

  • Byzantine Generals problem – consensus between various parties without a leader in distributed computing

Alogrithms-

  • proof-of-work algorithm (pow)

Setup BTCPay server in Azure

BTCPay Server is a self-hosted, open-source cryptocurrency payment processor. It’s secure, private, censorship-resistant and free.

Refer this link

Create a Resource group in Azure. I create this in West Us region.

Choose the template from the provided link and should take straight to your Azure subscription-

Enter the valid Vm Size and the supported crypto payment.

Select the Network – Mainnet, TestNet or regtest

Select the Ubuntu version. You may select the latest

Resources in Azure

This should create following resources in Azure in the selected resource group-

Navigate to BTCPayServerPublicIP resource. This should show the dns name.

This is your BTC pay admin portal.

Register Admin user

First time when you access the Btc Pay server should ask you to register a user. This user will be a owner.

Login to BTC pay server

Login with the newly created user

You will be asked to configure the lightining network and create a wallet.

Configuring the wallet and lightning network will follow in next blog along with integration with integration with commerce system such as Order Cloud.

Stay tuned to know how to configure this which should ulitmately sync the nodes as shown in below screen.

Loading

Indexing Bitcoin Transaction Database

By default Bitcoin Core builds a database containing only the transactions for the user’s wallet.

Wallet transactions can be retireved using JSON RPC API gettransaction command.

But if you want to retrieve any transaction within the node use command getrawtransaction. This command will search transactions in the index.

bitcoin.conf file set txindex

Bitcoin daemon or GUI uses conf file to load settings. On the first bitcoind run it will ask to create a config file.

Set txindex=1 in the config file before running the daemon. If the indexing is enabled the bitcoin daemon then should start synching the blocks and index.

bitcond -reindex option

If the txindex is not set in config before the first run and if later you want to index the database use -reindex option.

Re-index should take a while. To improve perfromance disable -printtoconsole option

bitcoind -reindex -rpcuser=xxxx -rpcpassword=xxxxx

bitcond -txindex option

If the txindex is not set in config before the first run and if later you want to index the database use -txindex option.

bitcoind -txindex -rpcuser=xxxx -rpcpassword=xxxxx

XM CLoud Dev – How to set background image using rendering parameters

This is a very common scenario where a background image needs to be set to certain components. Banner’s on any page on your website is a very common place to have a background image.

Note: This is not specific to XM Cloud but for any Headless implementation

Foundation Head already has an example on setting the background image using params. In this blog post will explore how this works and where in Sitecore the image can be applied. Will see how this can applied using Rendering Parameters and using OOTB _Background Image item.

Applying background image using rendering parameters

Background image can be applied to container. If you are using Foundation Head repo you can find this component OOTB.

Thre Container rendering is at following lcoation in Sitecore –

/sitecore/layout/Renderings/Feature/JSS Experience Accelerator/Page Structure/Container

Note Other properties- IsRenderingsWithDynamicPlaceholders and IsRenderingsWithDynamicPlaceholders is set to true

Rendering parameter is located – /sitecore/templates/Feature/JSS Experience Accelerator/Page Structure/Rendering Parameters/Container

Rendering paramter template has the BackgroundImage field. The background image will be set based on the image selected in this field.

How the image is set in Head

Lets see background image set in nextjs (sxastarter) Container.tsx

// image string from the rendering parameters
 let backgroundImage = props.params.BackgroundImage as string;
  let backgroundStyle: { [key: string]: string } = {};
  console.log('backgroundImage1');
  console.log(backgroundImage);
  if (backgroundImage) {
    const prefix = `${sitecoreContext.pageState !== 'normal' ? '/sitecore/shell' : ''}/-/media/`;
    backgroundImage = `${backgroundImage?.match(BACKGROUND_REG_EXP)?.pop()?.replace(/-/gi, '')}`;
    backgroundStyle = {
      backgroundImage: `url('${prefix}${backgroundImage}')`,
    };
  }

  return (
    <div className={`component container-default ${styles}`} id={id ? id : undefined}>

// style applied to <div> having background image
      <div className="component-content" style={backgroundStyle}>
        <div className="row">
          <Placeholder name={phKey} rendering={props.rendering} />
        </div>
      </div>
    </div>
  );
};

Lets see this in working in experience editor and rendering host

In the experience editor main section add a container component.

Once the rendering is added, goto “Edit component properties” and add an background image

Now you are able to see the background image applied ot container and I have added RichText in containerto show the image in background-

Rendering Host displays the image in background-

Nested containers to apply differnt background image or component

If you add only one container the image will be applied to the main section.

To resolve this you can add a container within main container. add mutiple containers as per your requirements. To set the background image to specific container in this example contianer-2 select the parent(i.e. container) and set the image by Editing the Component properties

This should apply the different images for various other sections in the sampe page and since the Container rendering has IsRenderingsWithDynamicPlaceholders property set this should create a unique Id for each container.

Here for example container-2 and container-3 is a child of container-1

Rendering Host displays banckgroung images with there respective components-

Isusue- Here you can see there is a white patch when applied to child container and the image is applied to inner div.

To resolev this apply the image to the outer div instead in container.tsx

return (
    <div className={`component container-default ${styles}`} style={backgroundStyle} id={id ? id : undefined}> // backgroundStyle added
      <div className="component-content"> // backgroundStyle removed
        <div className="row">
          <Placeholder name={phKey} rendering={props.rendering} />
        </div>
      </div>
    </div>
  );

Here you can seee a full width background image

Hope these tips helps.